Adgower's avatar
Level 14

Best Way to Convert this string to time?

I need to convert these strings into a start_date and end_date I get the duration in minutes, date, and time.

Example:

$duration = 60;
$date = 08/13/2020;
$time = 2:00; // PM

I can

return Carbon::createFromFormat('d-m-Y', $date);

I need the final output:

$start_date and $end_date format: YYYY-MM-DD HH:MI:SS with the difference between the two using the duration.

Thanks

0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Something like this?

$start = Carbon::createFromFormat('d-m-Y g:i A', $date. ' '. $time. ' PM');
$end = $start->copy()->addSeconds($seconds);
1 like
Adgower's avatar
Level 14

@sinnbeck

Thank you.

I have this so far:

$hour = Str::of($request->appointment_time)->substr(0, 2);
        $hourConverted = $hour;

        if (strval($hour) >= 1 && strval($hour) <= 5) {
            $hourConverted = strval($hour) + 12;
        }

        $time = $hourConverted . Str::of($request->appointment_time)->substr(2, 3);

        return Carbon::createFromFormat('d-m-Y H:i', $request->appointment_date . ' ' . $time);

appointment_time = 02:00 appointment_date = 08-18-2020

returns:

"2021-06-08T14:00:00.000000Z"

This is wrong. Have any tips?

Adgower's avatar
Level 14

@snapey thank you very helpful information, but its still returning 2021 instead of 2020 as the year and the month and day are wrong based upon the input

return Carbon::createFromFormat('d-m-Y H:i', $request->appointment_date . ' ' . $time)->format('Y-m-d h:i:s');

returns

2021-06-08 02:00:00
Adgower's avatar
Level 14

Thanks guys I got it. I had the create from Format wrong... should have been m-d-Y based upon input.

Please or to participate in this conversation.