How to calculate a date difference in calendar months? - php

$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.

Related

Add number of days to datetime and then find difference in days between two dates

I have saved a date in mysql table in date('Y-m-d H:i:s') format
$blacklisted_date = "2018-07-22 17:57:24";
$blacklisted_days = 7;
$now = date('Y-m-d H:i:s');
I want to add $blacklisted_days to $blacklisted_date
$result_date = $blacklisted_date + $blacklisted_days;
and then want to find the difference in days between the $result_date and $now.
$diff_days = $result_date - $now;
I believe this code block will help you solve the problem.
$blacklisted_date = "2018-07-22 17:57:24";
$blacklisted_days = 7;
$now = date('Y-m-d H:i:s');
$result_date = date('Y-m-d H:i:s', strtotime($blacklisted_date . '+'. $blacklisted_days.' days'));
if( $result_date > $now ){
$datediff = strtotime($result_date) - strtotime($now);
}else{
$datediff = strtotime($now) - strtotime($result_date);
}
$diff_days = round( $datediff / (60 * 60 * 24));
You can do it easily using DateTime class, look here:
$blacklisted_date = "2018-07-22 17:57:24";
$blacklisted_days = 7;
$date1 = new DateTime($blacklisted_date); // blacklisted
$date1->add(new DateInterval("P{$blacklisted_days}D")); // add N days
$date2 = new DateTime(); // now
$interval = $date1->diff($date2); // get diff
echo $interval->days; // in days
I hope it's really clear to understand

Calculate difference between to unix epoch date times?

I need to be able to find out the difference between two unix epoch times.
I am trying this at the moment
$interval = $nextFile-$firstFile;
($nextFile would equal "1452182820", $firstFile would equal "1452004380")
This gets me a result of "178440".
Is taking away two epoch date times away from each other valid? Or should i find the difference another way.
Try This May be help ful
<?php
$nextFile = '1452182820';
$firstFile = '1452004380';
$n = date('d-m-Y H:i:s',$nextFile);
$f = date('d-m-Y H:i:s',$firstFile);
$Date1 = date("Y-m-d", strtotime($n));
$Date2 = date("Y-m-d", strtotime($f));
$datetime1 = new DateTime($Date1);
$datetime2 = new DateTime($Date2);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

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');

Adding date or time in datetime format to another datetime

WHAT I AM DOING
I want to find the difference between 2 datetime and add it to another datetime. I am only able to get the difference in Y-m-d H:i:s format.
CODE
$begin = new DateTime($start);
$finish = new DateTime($end);
$diff = $begin->diff($finish);
$difference = $diff->format("%Y-%M-%D %H:%I:%S");
Here I want to add $difference to another datetime say $finaldate. If its not possible is there any way of getting the difference in only minutes, then i could use $date->modify("+$difference minutes");
*This is a method using DateTime:*
$begin = new DateTime($start);
$finish = new DateTime($end);
$difference = $finish->format('U') - $begin->format('U');
// working version
$minutesDiff = round(($difference/60), 0);
$finalDate = new DateTime();
$finalDate->modify(sprintf('+%s minutes', $minutesDiff));
edit
added missing bracket
edit2
version without ->diff() method
What about:
$begin = strtotime($start);
$finish= strtotime($end);
$diff = $finish-$begin;
$finaldate = strtotime($finaldate)+$diff;
echo date("Y-M-D h-i-s",$finaldate);

Setting a time and date and adding to it in PHP

Basically am trying to set a time and a date in PHP then set a time gap which will range between minutes, loop through between a start time and end time echoing something out for each one. Have tried loads of different ways and cant seem to figure a way to set a date and add to it.
This seems the best script I have modified so far:
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
$newendtime = $endtime->format('Y-m-d H:i');
$timedate = new DateTime('2012-01-01 09:00');
while($stamp < $newendtime)
{
$time = new DateTime($timedate);
$time->add(new DateInterval('PT' . $minutes . 'M'));
$timedate = $time->format('Y-m-d H:i');
echo $timedate;
}
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
//modified the start value to get something _before_ the endtime:
$time = new DateTime('2012-01-01 8:00');
$interval = new DateInterval('PT' . $minutes . 'M');
while($time < $endtime){
$time->add($interval);
echo $time->format('Y-m-d H:i');
}
Do everything in seconds, and use php's time(), date(), and mktime functions.
In UNIX Time, dates are stored as the number of seconds since Jan 1, 1970.
You can render UNIX Timestamps with date().
$time = time(); // gets current time
$endtime = mktime(0,0,0, 1, 31, 2012); // set jan 31 # midnight as end time
$interval = 60 * 5; // 300 seconds = 5 minutes
while($time < $endtime){
$time += $interval;
echo date("M jS Y h:i:s a",$time) . "<br>"; // echos time as Jan 17th, 2012 1:04:56 pm
}
date reference:
http://us3.php.net/manual/en/function.date.php (includes superb date format reference too)
mktime reference: http://us2.php.net/mktime
time() only gets the current time, but just for kicks n' giggles: http://us2.php.net/time
And, it's super easy to store in a database!
This function will let you add date to your existing datetime. This will also preserves HH:MM:SS
<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
date('d',$cd)+$day, date('Y',$cd)+$yr));
return $newdate;
}
?>
Usage:
add_date($date,12,0,0);
where $date is your date.

Categories