Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get php DateInterval in total 'minutes'

Tags:

php

datetime

I am trying to get the PHP "DateInterval" value in "total minutes" value. How to get it? Seems like simple format("%i minutes") not working?

Here is the sample code:

$test = new \DateTime("48 hours"); $interval = $test->diff(new \DateTime()); 

Now if I try to get the interval in total days, its fine:

echo $interval->format('%a total days'); 

It is showing 2 days as output, which is totally fine. What I am trying to get if to get the value in "total minutes", so I tried:

echo $interval->format('%i total minutes'); 

Which is not working. Any help appreciated to get my desired output.

like image 474
Rana Avatar asked May 27 '13 15:05

Rana


People also ask

How can I get minutes in PHP?

$min = $interval ->days * 24 * 60; $min += $interval ->h * 60; $min += $interval ->i; // Printing the Result in Minutes format.

What is Dateinterval in PHP?

Represents a date interval. A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTimeImmutable's and DateTime's constructors support.

How can I get different time in PHP?

Use date_diff() Function to Get Time Difference in Minutes in PHP. We will use the built-in function date_diff() to get time difference in minutes. For this, we need a start date and an end date. We will calculate their time difference in minutes using the date_diff() function.

What is date interval?

The span of time between a specific start date and end date.


2 Answers

abs((new \DateTime("48 hours"))->getTimestamp() - (new \DateTime)->getTimestamp()) / 60 

That's the easiest way to get the difference in minutes between two DateTime instances.

like image 195
deceze Avatar answered Sep 19 '22 07:09

deceze


If you are stuck in a position where all you have is the DateInterval, and you (like me) discover that there seems to be no way to get the total minutes, seconds or whatever of the interval, the solution is to create a DateTime at zero time, add the interval to it, and then get the resulting timestamp:

$timeInterval      = //the DateInterval you have; $intervalInSeconds = (new DateTime())->setTimeStamp(0)->add($timeInterval)->getTimeStamp(); $intervalInMinutes = $intervalInSeconds/60; // and so on 
like image 42
Neil Townsend Avatar answered Sep 20 '22 07:09

Neil Townsend