Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to subtract two dates and times to get difference

Tags:

php

datetime

i have to sent an email when a user register email contain a link that is become invalid after six hours what i m doing when email is sent i update the db with field emailSentDate of type "datetime" now i got the curent date and time and has made to the same formate as it is in db now i want to find that both these dates and time have differenc of 6 hours or not so that i can make link invalid but i donot know how to do this

my code is look like this i m using hardcoded value for db just for example

$current_date_time=date("Y-m-d h:i:s");
$current=explode(" ",$current_date_time);
$current_date=$current[0];
$current_time=$current[1];
$db_date_time="2010-07-30 13:11:50";
$db=explode(" ",$db_date_time);
$db_date=$db[0];
$db_time=$db[1];

i do not know how to proceed plz help

like image 889
user403269 Avatar asked Jul 30 '10 11:07

user403269


2 Answers

<?php
//$now = new DateTime(); // current date/time
$now = new DateTime("2010-07-28 01:11:50");
$ref = new DateTime("2010-07-30 05:56:40");
$diff = $now->diff($ref);
printf('%d days, %d hours, %d minutes', $diff->d, $diff->h, $diff->i);

prints 2 days, 4 hours, 44 minutes

see http://docs.php.net/datetime.diff

edit: But you could also shift the problem more to the database side, e.g. by storing the expiration date/time in the table and then do a query like
... WHERE key='7gedufgweufg' AND expires<Now()
Many rdbms have reasonable/good support for date/time arithmetic.

like image 168
VolkerK Avatar answered Jan 04 '23 10:01

VolkerK


What you can do is convert both of your dates to Unix epoch times, that is, the equivalent number of seconds since midnight on the 31st of December 1969. From that you can easily deduce the amount of time elapsed between the two dates. To do this you can either use mktime() or strtotime()

All the best.

like image 22
Adam Avatar answered Jan 04 '23 09:01

Adam