user7435594
user7435594

Reputation:

{Carbon} Convert time in HH:MM:SS format into seconds in Laravel?

I want to convert the time which I got from $scheduleTime = Carbon::createFromTimestampUTC($scheduleTimestamp)->toTimeString(); which is currently giving me 07:32:40 now I want to convert it into seconds only using Carbon library is this possible to do so if yes then how?

Upvotes: 8

Views: 29949

Answers (5)

LavrenovPavel
LavrenovPavel

Reputation: 139

private function convertTimeToSecond(string $time): int
{
    $d = explode(':', $time);
    return ($d[0] * 3600) + ($d[1] * 60) + $d[2];
}

Example, after 2 year...

Upvotes: 3

BM2ilabs
BM2ilabs

Reputation: 532

you could use

$scheduleTime =\Carbon\Carbon::createFromTimestampUTC($scheduleTimestamp)->diffInMinutes()

to display the time in minute or

$scheduleTime =\Carbon\Carbon::createFromTimestampUTC($scheduleTimestamp)->diffInSeconds() 

to display it in second

Upvotes: 3

user7435594
user7435594

Reputation:

well, its there in carbon itself just use secondsSinceMidnight() and you are good to go.

 $scheduleTimeSeconds = Carbon::createFromTimestampUTC($scheduleTimestamp)->secondsSinceMidnight();

Upvotes: 5

Sarnodeep Agarwalla
Sarnodeep Agarwalla

Reputation: 237

You can try this it will return only the seconds

$scheduleTime =\Carbon\Carbon::createFromTimestampUTC($scheduleTimestamp)->second; or

$scheduleTime =\Carbon\Carbon::createFromTimestampUTC($scheduleTimestamp)-> diffInSeconds();

Upvotes: 1

Sapnesh Naik
Sapnesh Naik

Reputation: 11636

Try this,

$scheduleTime = Carbon::createFromTimestampUTC($scheduleTimestamp)->toTimeString();

$sec = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $scheduleTime);

sscanf($sec, "%d:%d:%d", $hours, $minutes, $seconds);

$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;

Upvotes: 0

Related Questions