Check a date interval with strtotime in php - 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";
}

Related

PHP - Difference Between 2 Dates in Days

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

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

PHP days difference

Hello i'm trying to make a php script that compares the date from one of my database records and todays date, if the difference in days is greater than 3, it will come out to true.
example:
$todays_date = date("Y-m-d"); <-- Todays date
$deal_date = $data["Deal Date"]; <-- Date from database
$interval = date_diff($todays_date, $deal_date); <--Difference
if($interval >= 3)
{
(something)
}
but every time i try this i get an error "date_diff() expects parameter 1 to be DateTime, string given" i know that to use date_diff both arguments have to be datetime, but i'm not sure how to get today's date in date and how to convert the date from the database into datetime.
Try this code:
$date1 = new DateTime('now');
$date2 = new DateTime($data['Deal Date']);
$interval = $date1->diff($date2);
if ($interval->format('%a') >= 3) {
...
}
More examples in PHP date_diff documentation.
CORRECT SYNTAX IS:
<?php
$datetime1 = date_create('now');
$datetime2 = date_create($data["Deal Date"];);
$interval = date_diff($datetime1, $datetime2);
$diff = $interval->format('%a');
if($diff >= 3)
{
(something)
}
?>

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.

Elegant way to get the count of months between two dates?

Let's assume I have two dates in variables, like
$date1 = "2009-09-01";
$date2 = "2010-05-01";
I need to get the count of months between $date2 and $date1($date2 >= $date1). I.e. i need to get 8.
Is there a way to get it by using date function, or I have to explode my strings and do required calculations?
Thanks.
For PHP >= 5.3
$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-05-01");
var_dump($d1->diff($d2)->m); // int(4)
var_dump($d1->diff($d2)->m + ($d1->diff($d2)->y*12)); // int(8)
DateTime::diff returns a DateInterval object
If you don't run with PHP 5.3 or higher, I guess you'll have to use unix timestamps :
$d1 = "2009-09-01";
$d2 = "2010-05-01";
echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); // 8
But it's not very precise (there isn't always 30 days per month).
Last thing : if those dates come from your database, then use your DBMS to do this job, not PHP.
Edit: This code should be more precise if you can't use DateTime::diff or your RDBMS :
$d1 = strtotime("2009-09-01");
$d2 = strtotime("2010-05-01");
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$i = 0;
while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
$i++;
}
echo $i; // 8
Or, if you want the procedural style:
$date1 = new DateTime("2009-09-01");
$date2 = new DateTime("2010-05-01");
$interval = date_diff($date1, $date2);
echo $interval->m + ($interval->y * 12) . ' months';
UPDATE: Added the bit of code to account for the years.
Or a simple calculation would give :
$numberOfMonths = abs((date('Y', $endDate) - date('Y', $startDate))*12 + (date('m', $endDate) - date('m', $startDate)))+1;
Accurate and works in all cases.
This is another way to get the number of months between two dates:
// Set dates
$dateIni = '2014-07-01';
$dateFin = '2016-07-01';
// Get year and month of initial date (From)
$yearIni = date("Y", strtotime($dateIni));
$monthIni = date("m", strtotime($dateIni));
// Get year an month of finish date (To)
$yearFin = date("Y", strtotime($dateFin));
$monthFin = date("m", strtotime($dateFin));
// Checking if both dates are some year
if ($yearIni == $yearFin) {
$numberOfMonths = ($monthFin-$monthIni) + 1;
} else {
$numberOfMonths = ((($yearFin - $yearIni) * 12) - $monthIni) + 1 + $monthFin;
}
I use this:
$d1 = new DateTime("2009-09-01");
$d2 = new DateTime("2010-09-01");
$months = 0;
$d1->add(new \DateInterval('P1M'));
while ($d1 <= $d2){
$months ++;
$d1->add(new \DateInterval('P1M'));
}
print_r($months);
Using DateTime, this will give you a more accurate solution for any amount of months:
$d1 = new DateTime("2011-05-14");
$d2 = new DateTime();
$d3 = $d1->diff($d2);
$d4 = ($d3->y*12)+$d3->m;
echo $d4;
You would still need to handle the leftover days $d3->d if your real world problem is not as simple and cut and dry as the original question where both dates are on the first of the month.
This is a simple method I wrote in my class to count the number of months involved into two given dates :
public function nb_mois($date1, $date2)
{
$begin = new DateTime( $date1 );
$end = new DateTime( $date2 );
$end = $end->modify( '+1 month' );
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($begin, $interval, $end);
$counter = 0;
foreach($period as $dt) {
$counter++;
}
return $counter;
}
In case the dates are part of a resultset from a mySQL query, it is much easier to use the TIMESTAMPDIFF function for your date calculations and you can specify return units eg. Select TIMESTAMPDIFF(MONTH, start_date, end_date)months_diff from table_name
strtotime is not very precise, it makes an approximate count, it does not take into account the actual days of the month.
it's better to bring the dates to a day that is always present in every month.
$date1 = "2009-09-01";
$date2 = "2010-05-01";
$d1 = mktime(0, 0, 1, date('m', strtotime($date1)), 1, date('Y', strtotime($date1)));
$d2 = mktime(0, 0, 1, date('m', strtotime($date2)), 1, date('Y', strtotime($date2)));
$total_month = 0;
while (($d1 = strtotime("+1 MONTH", $d1)) <= $d2) {
$total_month++;
}
echo $total_month;
I have used this and works in all conditions
$fiscal_year = mysql_fetch_row(mysql_query("SELECT begin,end,closed FROM fiscal_year WHERE id = '2'"));
$date1 = $fiscal_year['begin'];
$date2 = $fiscal_year['end'];
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$te=date('m',$ts2-$ts1);
echo $te;

Categories