pi9
Posts: 142
Joined: Wed Jun 10, 2015 3:32 pm

PHP date_diff question

Sun Apr 15, 2018 4:25 am

Hi,
Can you tell me what is wrong with this code? I am trying to get the date difference in minutes.
$now prints ok
$date1 prints ok
I get blank for $interval
$date1 is in the same format that I will be getting from mysql database.

<?php
$now = date("Y-m-d H:i:s");
$date1 = date('2018-04-15 00:05:00');

$interval = date_diff($now, $date1);
echo $interval;
?>

User avatar
rpdom
Posts: 16972
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: PHP date_diff question

Sun Apr 15, 2018 5:33 am

Probably because date() returns a string, while date_diff requires a datetime object (see http://php.net/manual/en/datetime.diff.php for some examples of use).

I wouldn't do it that way. I'd convert the dates to unix timestamps (seconds since the "Epoch", 01/10/1970 00:00:00) and subtract one from the other and divide by 60 to get minutes.

Code: Select all

<?php

$now = time();

$date1 = strtotime('2018-04-15 00:05:00');

$interval = intval(($now - $date1) / 60);
echo "interval is $interval\n";
?>

pi9
Posts: 142
Joined: Wed Jun 10, 2015 3:32 pm

Re: PHP date_diff question

Sun Apr 15, 2018 3:10 pm

Thanks for the suggestion. I experimented with similar code before, but I got some results that made no sense.

1523804700 <- date of today at 11:05
1523804865 <- now at 11:09
interval is 25396714 <- this is the difference.

i can't make any sense of those numbers

User avatar
DougieLawson
Posts: 38784
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: PHP date_diff question

Sun Apr 15, 2018 3:18 pm

pi9 wrote:
Sun Apr 15, 2018 3:10 pm
Thanks for the suggestion. I experimented with similar code before, but I got some results that made no sense.

1523804700 <- date of today at 11:05
1523804865 <- now at 11:09
interval is 25396714 <- this is the difference.

i can't make any sense of those numbers
1523804700 is 15:05:00
1523804700 is 15:07:45

Your maths has gone wrong.
1523804865 minus 1523804700 equals 165 seconds.
165/60 == 2.75 minutes.
Last edited by DougieLawson on Sun Apr 15, 2018 4:09 pm, edited 1 time in total.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

pi9
Posts: 142
Joined: Wed Jun 10, 2015 3:32 pm

Re: PHP date_diff question

Sun Apr 15, 2018 3:57 pm

Thanks. I found the problem. I had a couple of test codes and used the wrong variable. $date instead of $date1.

Return to “Other programming languages”