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

5

8

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?

Yepez answered 17/5, 2017 at 7:36 Comment(5)
If I understood you correctly, you want to get unix timestamp format? If that's the case just append ->timestamp like Carbon::createFromTimestampUTC($scheduleTimestamp)->timestamp;Fluor
Possible duplicate of Convert time in HH:MM:SS format to seconds only?Aguila
Change ->toTimeString() to ->format('s')Secundines
@hopesfall he wants it in Carbon format used by laravelSecundines
nope I want whole time in seconds is it possible in carbon with getting involved into regular expression messYepez
Y
5

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

 $scheduleTimeSeconds = Carbon::createFromTimestampUTC($scheduleTimestamp)->secondsSinceMidnight();
Yepez answered 17/5, 2017 at 9:40 Comment(0)
R
3

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

Rally answered 2/11, 2017 at 13:54 Comment(0)
C
3
private function convertTimeToSecond(string $time): int
{
    $d = explode(':', $time);
    return ($d[0] * 3600) + ($d[1] * 60) + $d[2];
}

Example, after 2 year...

Clue answered 26/3, 2020 at 22:21 Comment(0)
Z
1

You can try this it will return only the seconds

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

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

Zamboanga answered 17/5, 2017 at 7:41 Comment(0)
O
0

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;
Octroi answered 17/5, 2017 at 7:42 Comment(3)
looks like I need to go for that core thing nothing in carbon for me?Yepez
@BhavikBamania I'm sorry I don't have any idea on how to do it using Carbon libraryOctroi
it's fine I got the answer check my answer :)Yepez

© 2022 - 2024 — McMap. All rights reserved.