pi9
Posts: 43
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: 12578
Joined: Sun May 06, 2012 5:17 am
Location: 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: 43
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: 32993
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

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.
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

2012-18: 1B*5, 2B*2, B+, A+, Z, ZW, 3Bs*3, 3B+

Any DMs sent on Twitter will be answered next month.

pi9
Posts: 43
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”

Who is online

Users browsing this forum: nahuavrilero and 3 guests