PHP - Difference Between 2 Dates in Days - php

I have the following:
$dateStart = get_post_meta( get_the_ID(), 'startdate' , true);
$dateStart = DateTime::createFromFormat('d/m/Y h:i:s', $dateStart);
$dStart = $dateStart->format('d/m/y');true);
$dEnd = date("d/m/y");
echo $dStart .'-'.$dEnd;
This outputs 12/06/15-28/10/15 but for the life of me I can't work out how to get the difference in days between the two dates.
Any advice? I've tried a few things but they error out each time.
Thanks

The most secure way I found to compute the number of days between a date DateTime $a and another on DateTime $b is to rely on their timestamps at midnight:
protected static function diffDays(DateTime $a, DateTime $b)
{
return round(
($a->setTime(0, 0, 0)->getTimestamp() - $b->setTime(0, 0, 0)->getTimestamp())
/ 86400 // 60 * 60 * 24 = 86400s in 24h
);
}
Work very well for me :)
Note: I use hard coded value 86400 in order to reduce useless processing time calculating 60 * 60 * 24

Use this(Working Example)
date_default_timezone_set("Asia/Colombo");
$dateStart = get_post_meta( get_the_ID(), 'startdate' , true);
$datetime1 = new DateTime(date('Y-m-d', $dateStart));
$datetime2 = new DateTime(date('Y-m-d', $dateStart)));
$interval = $datetime1->diff($datetime2);
$date_diff = $interval->format('%R%a days');
echo "Difference is ".$date_diff

Use DateTime::diff - http://php.net/manual/en/datetime.diff.php
$dateStart = DateTime::createFromFormat('d/m/Y h:i:s', $dateStart);
$dateEnd = new DateTime();
$difference = $dateStart->diff($dateEnd);
Also note that not passing the end to diff() will assume now. So this would work also, in your particular example:
$dateStart = DateTime::createFromFormat('d/m/Y h:i:s', $dateStart);
$difference = $dateStart->diff();

$daysBefore = round(abs(strtotime(Date("l, d F Y"))-strtotime($dateStart))/86400);
$daysAfter = round(abs(strtotime(Date("l, d F Y"))-strtotime($dateEnd))/86400);
This seemed to be the only way I could get it to work

Related

Check a date interval with strtotime in php

I need a little help with this code:
$key['time_stamp'] = '2016-09-02 16:56:25';
$datetime1 = strtotime(date($key['time_stamp']));
$datetime2 = strtotime(date('Y-m-d H:m:s'));
$interval = $datetime2 - $datetime1;
$val = 45 * 60 * 1000;
if ($interval > $val) { }
My purpose is to check if the $interval between two dates is greater than 45 mins.
$key['time_stamp'] is 2016-09-02 16:56:25 and datetime2 is the current date time. Why the if condition is never true?!
Did I miss something stupid or what?!
If $key['time_stamp'] is '2016-09-02 16:56:25', shouldn't it be
$datetime1 = strtotime ( $key['time_stamp'] );
Instead of
$datetime1 = strtotime ( date ($key['time_stamp']) );
?
This line:
$val = 45*60*1000;
gives 45 minutes in millisecond, I guess you want:
$val = 45*60;
I find working with DateTime() objects easier to reason about, and they are transparently comparable in an if statement.
I'd like to suggest an alternative approach:
<?php
$key['time_stamp'] = '2016-09-02 16:56:25';
$then = new DateTime($key['time_stamp']);
$interval = new DateTime('-45 minutes');
if ($then < $interval) {
echo 'interval passed';
} else {
echo 'interval not passed';
}
This yields:
interval passed
Hope this helps :)
One caveat that's not applicable in your case but it's worth mentioning: If you create a DateTime() object with a UNIX timestamp using DateTime::createFromFormat() be sure to check that both DateTime() objects have the same timezone.
You made two mistakes:
the minutes in the $format parameter of the date function have to be expressed as i (and not m, as you did).
$interval is measured in seconds (so you don't have to multiply by 1000, as if they were milliseconds).
So your code should be written as follows:
$key['time_stamp'] = '2016-09-02 16:56:25';
$datetime1 = strtotime(date($key['time_stamp']));
$datetime2 = strtotime(date('Y-m-d H:i:s'));
$interval = $datetime2 - $datetime1;
$val = 45 * 60;
if ($interval > $val) { }
Here is the solution of your query.
$key['time_stamp'] = "2016-09-02 16:56:25";
$datetime1 = strtotime ( date ($key['time_stamp']) );
$datetime2 = strtotime ( date('Y-m-d H:i:s'));
$interval = round(($datetime2 - $datetime1)/ 60); //interval in minutes
$val = 45; //45 minutes
if ($interval > $val) {
echo "Success";
}

add hours:min:sec to date in PHP

I am trying to add hh:mm:ss with the date. How can i do it?
I tried with the following but it works when the hour is string, but when adding time is similar to MySQL Date time it is not working.
$new_time = date("Y-m-d H:i:s", strtotime('+5 hours'));
I am trying to get solution for the following:
$timeA= '2015-10-09 13:40:14';
$timeB = '03:05:01'; // '0000-00-00 03:05:01'
OutPut:
$timeA + $timeB = 2015-10-09 16:45:15 ?
How Can I Add this?
Use DateInterval():
$timeA = new DateTime('2015-10-09 13:40:14');
$timeB = new DateInterval('PT3H5M1S'); // '03:05:01';
$timeA->add($timeB);
echo $timeA->format('Y-m-d H:i:s');
You would need to break your time down into the right DateInterval format but that is easily done with explode();
Here's how that might look:
$parts = array_map(function($num) {
return (int) $num;
}, explode(':', '03:05:01'));
$timeA = new DateTime('2015-10-09 13:40:14');
$timeB = new DateInterval(sprintf('PT%uH%uM%uS', $parts[0], $parts[1], $parts[2]));
$timeA->add($timeB);
echo $timeA->format('Y-m-d H:i:s');
Demo
print date('Y-m-d H:i:s',strtotime($timeA." +03 hour +05 minutes +01 seconds"));
Should work also.
So:
$timeA= '2015-10-09 13:40:14';
$timeB = vsprintf(" +%d hours +%d minutes +%d seconds", explode(':', '03:05:01'));
print date('Y-m-d H:i:s',strtotime($timeA.$timeB));
Can be the solution.
You may also convert the time into seconds with this approach from: Convert time in HH:MM:SS format to seconds only?
$time = '03:05:01';
$seconds = strtotime("1970-01-01 $time UTC");
Then you could add the seconds to
$currentTime = '2015-10-10 13:40:14';
$newTime = date("Y-m-d H:i:s", strtotime( $currentTime.'+'.$seconds.' seconds'));
If you prefer to use the DateTime objects offered by #John Conde, here are two ways to convert the time string into the format:
$formattedTime = preg_replace("/(\d{2}):(\d{2}):(\d{2})/","PT$1H$2M$3S","03:05:11");
or, as you read it from the database:
select concat(hour(last_modified),'H',minute(last_modified),'M',second(last_modified),'H') from people;
So a more general code approach would be:
$initial = 'some time';
$interval = 'the interval value';
$initialTime = new DateTime($initial);
$intervalTime = new DateInterval($interval);
$initialTime->add($intervalTime);
echo $initialTime->format('Y-m-d H:i:s');

Add current time to DateTime

I would like to add 5 days and current time to a date, which I have in string.
$date = new DateTime('2013-11-21');
date_add($date, date_interval_create_from_date_string('5 days'));
$curtime = date('H:i:s');
How to add current time to DateTime, or is there any other better way how to do it?
Just edit your last lane - I think it is the most objective solution to your problem. The rest of your code is correct.
$curtime = $date->format('Y-m-d H:i:s');
Remember that your second lane is just an alias to:
$date->add(DateInterval::createFromDateString('5 days'));
So the full code would be:
$date = new DateTime('2013-11-21');
$date->add(DateInterval::createFromDateString('5 days'));
$curtime = $date->format('Y-m-d H:i:s');
EDIT: I've just read your question again and you ask about adding current time to this date. If you want to add time, then you need to create it from current date. It's not the perfect solution, but I'm still working on it:
$now = new DateTime(date('1970-01-01 H:i:s'));
$date->add(DateInterval::createFromDateString($now->getTimestamp() . ' seconds'));
$curtime = $date->format('Y-m-d H:i:s');
echo $curtime;
EDIT2: I've corrected it much more, look at this code:
$date = new DateTime('2013-11-21');
$date->add(DateInterval::createFromDateString('5 days'));
$now = new DateTime('now');
$today = new DateTime(date('Y-m-d'));
$time = $today->diff($now);
$date->add($time);
echo $date->format('Y-m-d H:i:s');
EDIT3: And remember about time zones:
$date = new DateTime('2013-11-21', new DateTimeZone('Europe/Warsaw'));
$date->add(DateInterval::createFromDateString('5 days'));
$now = new DateTime('now', new DateTimeZone('Europe/Warsaw'));
$today = new DateTime(date('Y-m-d'), new DateTimeZone('Europe/Warsaw'));
$time = $today->diff($now);
$date->add($time);
echo $date->format('Y-m-d H:i:s');
And fiddle: http://sandbox.onlinephpfunctions.com/code/0080d18d18dd7e2fefa7dea7d961087f14ceb3df
You can add 5 days like this:
$nextX = time() + (5 * 24 * 60 * 60);
5 days * 24 hours * 60 mins * 60 secs
Try:
$date = '2013-11-21';
$date = strtotime($date);
$date = strtotime("+7 day", $date);
echo date('M d, Y', $date);
Try this
$hour_two = "2013-11-21";
$date = strtotime($hour_two);
$hour_two = $date + (5 * 24 * 60 * 60);
$hour_two=date('Y-m-d',$hour_two);
$currenttime = date('H:i:s');
$h = strtotime($currenttime);
$minute = date("i", $h);
$second = date("s", $h);
$hour = date("H", $h);
$new_time = $hour_two." ".$hour.":".$minute.":".$second;
echo $new_time."<br/>"; // here is your final date time
$timeto_string=strtotime($new_time); // test using strtotime
echo date('Y-m-d H:i:s',$timeto_string); // print by formating
$curtime = date('H:i:s');
$date = #date("Y-m-d H:i:s",strtotime($mydate.$curtime)) ;

How to find time difference between 2 dates in php

I want to get the time difference between 2 dates in minutes. The 2 dates are in the following format
date1='05-11-2012 11:25:00'
date2='06-11-2012 17:45:00'
$datetime1 = new DateTime('05-11-2012 11:25:00');
$datetime2 = new DateTime('06-11-2012 17:45:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); //return +1 days
//or
$datetime1 = date_create('05-11-2012 11:25:00');
$datetime2 = date_create('06-11-2012 17:45:00');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days'); //return +1 days
for php <5.3
$date1 = '05-11-2012 11:25:00';
$date2 = '06-11-2012 17:45:00';
$diff = floor(abs( strtotime( $date1 ) - strtotime( $date2 ) )/(60*60*24));
printf("%d days\n", $diff); //return 1 days
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>
For further reference please visit the following link
http://php.net/manual/en/datetime.diff.php
You neglected to indicate what format you'd like the time difference expressed in. If you're willing to work in seconds (which are easily converted), you could simply convert each date to a timestamp and then take the absolute difference using basic math. For instance, give $date1 = '05-11-2012 11:25:00' and $date2 = '06-11-2012 17:45:00':
$diff_seconds = abs( strtotime( $date1 ) - strtotime( $date2 ) );
And you could do whatever you like with the result.
$start_time = strtotime( "2012-10-12 11:35:00" );
$end_time = strtotime( "2012-10-13 12:42:50" );
echo round ( abs( $end_time - $start_time ) / 60,2 ). " minute";
This is different between two dates in MINUTES.

How to calculate a date difference in calendar months?

$time_start = mktime(12,0,0,1,1,2011);
$time_end = mktime(12,0,0,7,1,2011);
$format = '%m months';
$start_date = new DateTime(date(DATE_ATOM,$time_start));
$end_date = new DateTime(date(DATE_ATOM,$time_end));
$diff = $start_date->diff($end_date, true);
echo $diff->format($format);
Outputs "5 months", I guess because it's off by an hour due to DST. However, I need to calculate the difference in calendar months; is there another class/function that will do this?
Added some fixes:
if($time_start > $time_end) list($time_start, $time_end) = array($time_end, $time_start);
$time_end += (date('I',$time_end)-date('I',$time_start))*3600; // correct for DST
$start_date = new DateTime(date(DATE_ATOM,$time_start));
$end_date = new DateTime(date(DATE_ATOM,$time_end));
$start_date->modify('12pm'); // ignore time difference
$end_date->modify('12pm');
$diff = $start_date->diff($end_date);
echo $diff->format($format);
This seems to give the results I want, but I haven't fully tested it yet.
More fixes, based on Herbert's suggestions:
if($time_start > $time_end) list($time_start, $time_end) = array($time_end, $time_start);
$start_date = new DateTime();
$end_date = new DateTime();
$start_date->setTimestamp($time_start);
$end_date->setTimestamp($time_end);
$diff = $start_date->diff($end_date);
$hours = $diff->format('%h');
$mins = $diff->format('%i');
$secs = $diff->format('%s');
$start_date->setTime(12,0,0);//ignore time difference for date calculations
$end_date->setTime(12,0,0);
$diff = $start_date->diff($end_date);
$years = $diff->format('%y');
$months = $diff->format('%m');
$weeks = $diff->format('%w');
$days = $diff->format('%d');
Note that the $start_date->modify('12pm') wasn't actually doing anything at all. Not sure why it didn't error.
Update
After messing around with a lot of different ideas it occurred to me that timestamps are in GMT (UTC). date(DATE_ATOM,$time_start) is applying the default timezone. However, if you set the timestamp explicitly, DateTime will assume UTC — thus, no DST problem.
The following code seems to work regardless of timezone or DST.
<?php
$time_start = mktime(12,0,0,1,1,2011);
$time_end = mktime(12,0,0,7,1,2011)
$start_date = new DateTime();
$end_date = new DateTime();
$start_date->setTimestamp($time_start);
$end_date->setTimestamp($time_end);
$diff = $start_date->diff($end_date);
$format = '%m months';
echo $diff->format($format);
?>
I tested some edge cases — both date and time, and a variety of timezones — but I haven’t tested every possibility so if you come across an issue, I’d be interested in hearing about it.

Categories