質問

I am trying to get the number of minutes between two DateTimes in PHP:

$time = new DateTime($dateString);
$now = new DateTime;
$diff = $time->diff($now);

echo $diff->format('%m');

The result is always 0, although the DateTimes are several hours apart. How would I do this the right way?

役に立ちましたか?

解決

%m is for months. Minutes is %i:

echo $diff->format('%i');

他のヒント

Total number of minutes between 2 datetimes:

$diff = (new DateTime($string))->diff(new DateTime); # PHP >= 5.4.0
#$diff = date_diff(date_create($string), date_create()); # PHP >= 5.3.0
$minutes = ($diff->days * 24 + $diff->h) * 60 + $diff->i;

demo

In this case I would keep it simple and use the difference between timestamps/60:-

$minutes = ($date2->getTimestamp() - $date1->getTimestamp())/60;

See it working.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top