I have two dates in the format below:
Start Date = 30-10-2009
End Date = 30-11-2009
How, with PHP could I calculate the seconds between these two dates?
Parse the two dates into Unix timestamps using strtotime, then get the difference:
$firstTime = strtotime("30-10-2009");
$secondTime = strtotime("30-11-2009");
$diff = $secondtime - $firstTime;
The function strtotime() will convert a date to a unix-style timestamp (in seconds). You should then be able to subtract the end date from the start date to get the difference.
$difference_secs = strtotime($end_date) - strtotime($start_date);
I'd rather advice to use built in DateTime object.
$firstTime = new DateTime("30-10-2009");
$diff = $firstTime->diff(new DateTime("30-11-2009"));
As for me it's more flexible and OOP oriented.
In fact previous answer will give you a DateInterval object but not seconds. In order to get seconds with OOP approach you should do this:
$date1 = new DateTime("30-10-2009");
$date2 = new DateTime("30-11-2009");
$seconds = $date2->getTimestamp() - $date1->getTimestamp();
Related
I have two Datetimes like this (the dates being actually $vars)
$startTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/01 23:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/02 01:00');
I struggle with a (possibly pretty) simple problem: How could I determine if the two dates are on different calendar days?
I cannot do < as 2015/01/01 22:00 < 2015/01/01 23:00 would also be true. I can also not do this:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days;
as it gives me 0.
THIS gives me an idea about how to do it, but for javascript, what would be the equivalent for php?
//UPDATE
$startDate = $startTime->format('Y/m/d');
$endDate = $endTime->format('Y/m/d');
$diffDates = $startDate->diff($endDate);
$daysDiff = $diffDates->format('%d');
echo $daysDiff;
I think that might be the right approach now, thanks to the comments, but now I get Error: Call to a member function diff() on string
//UPDATE FOR CLARIFICATION WHAT I'M TRYING TO DO
I just want to have the difference in days, so for the above it would be '1' (although only 2 hours difference actually) and for example '2015/01/01 23:00' and '2015/01/03 17:00' would be '2'.
Just create the dates with time set to 00:00:00:
$startTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/01 00:00:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/02 00:00:00');
or reset time to zero on existing dates:
$startTime->setTime(0, 0, 0);
$endTime->setTime(0, 0, 0);
then it should work:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days; // 1
Bonus
If you want to work only with dates, remember to set the time to 00:00:00 in createFromFormat or reset it with setTime. If you won't provide time in createFromFormat PHP will set it to the current time:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
print $date->format('H:i:s'); //not 00:00:00
To fix it, you must either:
provide 00:00:00 time in format:
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2016-01-21 00:00:00');
prefix the date format with exclamation mark and omit the time, this will set the time to 00:00:00 automatically:
$date = DateTime::createFromFormat('!Y-m-d', '2016-01-21');
reset the time after creation:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
$date->setTime(0, 0);
I think this is one of the few situations where the use of strings for date calculations is justified:
function onDifferentDays(\DateTimeInterface $startTime, \DateTimeInterface $endTime){
return $startTime->format('Y-m-d')!==$endTime->format('Y-m-d');
}
This code should be easy to extend to include time zone.
There're other alternatives but I don't think they're normally worth the effort:
Compare element by element (day, month and year):
The PHP DateTime class doesn't offer dedicated functions, only format().
Normalize both dates to a common time and compare with == (not ===):
Unless you're using immutable objects you need to clone input or expect side effects
You also need to ensure that time exists in the active time zone though midnight is probably safe enough.
Whatever, YMMV ;-)
Comparing formatted dates is the right thing to do:
$a->format('Y-m-d') === $b->format('Y-m-d')
There is a method for that if you use Carbon:
$dt1->isSameDay($dt2)
So I recommend to use it instead of previous answers given here.
http://carbondoc/docs/#api-comparison
I want to get difference between 2 timestamps of format Y-m-d H:i:s in minutes in PHP.
The code used is,
$currentDate = date('Y-m-d H:i:s');
$userLastActivity = date($date);
$timeLapse = (($currentDate - $userLastActivity)/60);
Here, $date is obtained from database.
The value of $timeLapse is 0 in output. Please help.
Try using unix timestamp. Practically it measures the time in seconds from 1/1/1970 and it's a lot easier to use and understand than a php object.
$currentTimestamp = new DateTime()->getTimestamp();
$userLastActivity = date($date)->getTimestamp();
$timeLapse = (($currentDate - $userLastActivity)/60);
You should have the time saved as timestamp on the server too, in that case you could use the $date directly as a number, with no need for a conversion. And also, because it's universal, you can pass it around to javascript or any other language without any worries for conversion
Use strtotime to parse textual datetime into a Unix timestamp and substract $userLastActivity from $currentDate and divide by 60.
See if this helps -
<?php
$currentDate = strtotime(date('Y-m-d H:i:s'));
$date = "2016-10-11 02:40:50";
$userLastActivity = strtotime($date);
echo round(abs($currentDate - $userLastActivity) / 60). " minutes";
?>
For more details :strtotime
Change these 2 lines for a start, as I don't think dividing dates by 60 is gonna work to well.
$currentDate = time();
$userLastActivity = strtotime($date);
That way you have time stamps and not dates (string)
I have two Datetimes like this (the dates being actually $vars)
$startTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/01 23:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i', '2015/01/02 01:00');
I struggle with a (possibly pretty) simple problem: How could I determine if the two dates are on different calendar days?
I cannot do < as 2015/01/01 22:00 < 2015/01/01 23:00 would also be true. I can also not do this:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days;
as it gives me 0.
THIS gives me an idea about how to do it, but for javascript, what would be the equivalent for php?
//UPDATE
$startDate = $startTime->format('Y/m/d');
$endDate = $endTime->format('Y/m/d');
$diffDates = $startDate->diff($endDate);
$daysDiff = $diffDates->format('%d');
echo $daysDiff;
I think that might be the right approach now, thanks to the comments, but now I get Error: Call to a member function diff() on string
//UPDATE FOR CLARIFICATION WHAT I'M TRYING TO DO
I just want to have the difference in days, so for the above it would be '1' (although only 2 hours difference actually) and for example '2015/01/01 23:00' and '2015/01/03 17:00' would be '2'.
Just create the dates with time set to 00:00:00:
$startTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/01 00:00:00');
$endTime = \DateTime::createFromFormat('Y/m/d H:i:s', '2015/01/02 00:00:00');
or reset time to zero on existing dates:
$startTime->setTime(0, 0, 0);
$endTime->setTime(0, 0, 0);
then it should work:
$diff = $startTime->diff($endTime);
$days = $diff->format('%d');
echo $days; // 1
Bonus
If you want to work only with dates, remember to set the time to 00:00:00 in createFromFormat or reset it with setTime. If you won't provide time in createFromFormat PHP will set it to the current time:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
print $date->format('H:i:s'); //not 00:00:00
To fix it, you must either:
provide 00:00:00 time in format:
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2016-01-21 00:00:00');
prefix the date format with exclamation mark and omit the time, this will set the time to 00:00:00 automatically:
$date = DateTime::createFromFormat('!Y-m-d', '2016-01-21');
reset the time after creation:
$date = DateTime::createFromFormat('Y-m-d', '2016-01-21');
$date->setTime(0, 0);
I think this is one of the few situations where the use of strings for date calculations is justified:
function onDifferentDays(\DateTimeInterface $startTime, \DateTimeInterface $endTime){
return $startTime->format('Y-m-d')!==$endTime->format('Y-m-d');
}
This code should be easy to extend to include time zone.
There're other alternatives but I don't think they're normally worth the effort:
Compare element by element (day, month and year):
The PHP DateTime class doesn't offer dedicated functions, only format().
Normalize both dates to a common time and compare with == (not ===):
Unless you're using immutable objects you need to clone input or expect side effects
You also need to ensure that time exists in the active time zone though midnight is probably safe enough.
Whatever, YMMV ;-)
Comparing formatted dates is the right thing to do:
$a->format('Y-m-d') === $b->format('Y-m-d')
There is a method for that if you use Carbon:
$dt1->isSameDay($dt2)
So I recommend to use it instead of previous answers given here.
http://carbondoc/docs/#api-comparison
I have the following code which works on the first 2 lines, taking my start date, converting to unix timestamp, and then adding one day.
The 3rd line is trying to use the value that is then generated to use the date interval to find the date in 2 months.
Unfortunately, the date_add seems to return the error 'date_add() expects parameter 1 to be DateTime, integer given'.
Can anyone tell me how I accomplish this using unix timestamp?
$startdate = strtotime('2014/12/19 15:00');
$weekstart = $startdate - (date("N",$startdate)*60*60*24)+(60*60*24);
$enddate = date_add($weekstart, DateInterval::createfromDateString('2 months'));
Seems that you are wanting to create two different DateTime strings with different intervals. This should do it.
$startdate = new DateTime('2014/12/19 15:00');
$weekstart = $startdate->modify('+1 day');
$weekstart = $weekstart->format('U'); //change $weekstart to unix timestamp//
$enddate = $startdate->modify('+2 months');
$enddate = $enddate->format('U'); //change $enddate to unix timestamp//
So use a DateTime:
$startdate = new DateTime('2014/12/19 15:00');
internally DateTime's constructor will be using strtotime() anyways, giving you all the benefits (and risk) of strtotime()'s parsing logic, plus all the benefits of having the entire DateTime object available from the get-go.
The rest of your datemath can be accomplished using pure DateTime operations as well,w ithout having to do manual 60*60*24-type stuff.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to find number of days between two dates using php
Is there a quick and easy way to calculate the difference in days between two date strings in this format (YYYY-MM-DD) with PHP (not MySQL)?
$date1 = new DateTime("2010-07-06"); //inclusive
$date2 = new DateTime("2010-07-09"); //exclusive
$diff = $date2->diff($date1);
echo $diff->format("%a"); //3
(PHP 5.3 and higher only)
The only solution I see for PHP < 5.2 is to loop:
strtotime("-1 days");
strtotime("-2 days");
...
strtotime("-n days");
until we get to the unix timestamp of the first date. That's conceptually, you can do it in a much more efficient way, by first guessing the number of days with the timestamp difference of the two days and then testing the neighborhood.
Why dividing by 86400 doesn't work
date_default_timezone_set("Europe/Lisbon");
$date1 = strtotime("2010-03-28");
$date2 = strtotime("2010-03-29");
echo ($date2-$date1)/86400; //gives 0.95833333333333
$date1 = strtotime("2010-10-31");
$date2 = strtotime("2010-11-01");
echo ($date2-$date1)/86400; //gives 1.0416666666667
As Gordon correctly has pointed out, dividing by 86400 would be a valid solution for this problem if the timezone was set to 'UTC' before – just don't forget to restore it to the previous value after.
You can use this function to get the number of days between two date("Y-m-d H:i:s"):
function dateDiff($dateStart, $dateEnd)
{
$start = strtotime($dateStart);
$end = strtotime($dateEnd);
$days = $end - $start;
$days = ceil($days/86400);
return $days;
}
Copied from the Duplicate I've linked below the question.
The following SO questions might be of some help:
How to calculate the date difference between 2 dates using php
Dates difference with php
Calculate the difference between date/times in PHP
Date Difference in php?
Getting the difference between two time/dates using php?
More >>