Wishwajith Milinda
Wishwajith Milinda

Reputation: 97

How to convert hours to seconds in carbon PHP API extension

I want to convert "2 hours 11 mins"(string) to seconds in carbon is there's any way convert that string format into seconds in carbon? I am stuck with this, couldn't find a solution yet Thank you in advance...

Upvotes: 0

Views: 4004

Answers (4)

STA
STA

Reputation: 34678

There is a strtotime() function in PHP :

$t = strtotime("2 hours 11 mins");
echo (time() - $t) . " seconds ago";
// -7860 seconds ago

Upvotes: 0

OMR
OMR

Reputation: 12188

there is a third way:

use Carbon\CarbonInterval;


 $intervalue=CarbonInterval::make("2 hours 11 mins");

$intervalueInSeconds= $intervalue->totalSeconds;

Upvotes: 3

Sam Stevenson
Sam Stevenson

Reputation: 95

You don't need carbon to do it. Use native php functions.

  1. Use regex function to get $hours and $minutes.
  2. $seconds = $hours*3600 + $minutes*60;

Upvotes: 0

Tim Lewis
Tim Lewis

Reputation: 29258

Carbon has a useful modify() function:

https://carbon.nesbot.com/docs/#api-addsub

This function can handle a number of "magic" durations to change a Date to another one. Since Carbon works with time stamps, you'll need a base and an modified one, then compare them:

$base = Carbon\Carbon::now();                         // 2020-11-03 19:04:49.140462 UTC (+00:00)
$modified = $base->copy()->modify('2 hours 11 mins'); // 2020-11-03 21:15:49.140462 UTC (+00:00),
$diff = $base->diffInSeconds($modified);              // 7860

Note: the string passed to modify() can fail, but you'll receive an error if it does.

Upvotes: 1

Related Questions