calculate day difference between two unix timestamps at boundary values - php

I have two timestamps created against dates 02/09/2014 11:30pm and 03/09/2014 12:00am.
There is only 30 minutes difference between these timestamps but as date has changed from O2 October to 03 October, it should be calculated as a day.
My code is
$current_time_zone = isset($_COOKIE['IANA_timezone_key']) ? $_COOKIE['IANA_timezone_key'] : "";
$d1 = new DateTime(date('Y-m-d'), timezone_open($current_time_zone));
$d2 = new DateTime(date('Y-m-d'), timezone_open($current_time_zone));
$d1->setTimestamp($row["transitions_date"]); // $row["transitions_date"] has timestamp value
$d2->setTimestamp($curr_transition_in_date); // $curr_transition_in_date has timestamp value
$diff = date_diff($d1, $d2);
$day_difference = $diff->days;
Any help will be highly appreciated.

You could not expect your desired day difference from the returning object of date_diff() as it is based on the actual time difference. The easiest way would be to adjust it yourself.
$d1 = new DateTime(date('Y-m-d'));
$d2 = new DateTime(date('Y-m-d'));
$d1->setTimestamp($row["transitions_date"]);
$d2->setTimestamp($curr_transition_in_date);
$diff = date_diff($d1, $d2);
$day_difference = $diff->days;
echo 'Actual output from date_diff: '.$day_difference;
echo '<br>';
if($d2->format('H:i:s') < $d1->format('H:i:s')){
$day_difference++;
}
echo 'Corrected output: '.$day_difference;
Demo 1 for the different day, but same month and year.
Demo 2 for the same day, but different month and year.
Demo 3 for the same output.

Related

PHP: How to compare months and days( "m-d" dates) with year, month and days ("y-m-d" dates)

What is the best way to compare a month and day date ("m-d") with a date with the format "y-m-d".
for example:
$date1 = "2022-04-20";
$date2 = "2022-05-20";
$seasonStart = "03-15";
$seasonEnd = "04-30";
I want to know how many days between $date1 and $date2 are between $seasonStart and $seasonEnd.
You can use DateTime objects for the comparison.
$date1 = new DateTime($date1);
$date2 = new DateTime($date2);
For the seasonal dates, there are a couple of different ways you can do it depending on how you need it to work.
You can use the year from the given date rather than defaulting to the current year, if you want to see if those dates are within the season for the year in which they occur.
$year = $date1->format('Y');
$seasonStart = new DateTime("$year-$seasonStart");
$seasonEnd = new DateTime("$year-$seasonEnd");
If you only want to compare the date range to the season for the current year, then you can let the year default to the current one.
$seasonStart = DateTime::createFromFormat('m-d H:i', "$seasonStart 00:00");
$seasonEnd = DateTime::createFromFormat('m-d H:i', "$seasonEnd 00:00");
Then you can use this to calculate the number of days in the given range that are included in the season.
if ($date1 > $seasonEnd || $date2 < $seasonStart) {
// in this case the range does not overlap with the season at all
$days = 0;
} else {
$days = (max($seasonStart, $date1))->diff(min($seasonEnd, $date2))->days + 1;
}
<?php
$date = DateTime::createFromFormat('m-d', '02-15');
echo $date->format("Y-m-d");
$season=$date->getTimeStamp();
$current=time();
if ($current>$season) {
echo "Season has started!";
}
?>

How to find the Time Difference between a PM time and AM time?

In my form there are 2 Time Pickers where user can select a from time and to time. It doesn't have a date associated with it. And for a report generating purpose I've to calculate the time difference between them. It works perfectly to if the From and to Time is "06:00 to 10:00" but if the from and to time is "21:00 to 02:00" I get a time difference of 19 hours. Could you please help me to fix this.
For this case "21:00 to 02:00" the time difference should be 5 hours.
This is the Code
$datetime1 = new \DateTime('09:30 PM');
$datetime2 = new \DateTime('02:00 AM');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh');
exit;
The difference becomes negative If $totime is less than $fromtime.
DateInterval->invert == 1 indicates that. This is used with this short solution to correct the result.
$fromtime = '09:30 PM';
$totime = '02:00 AM';
$diff = date_create($fromtime)->diff(date_create($totime));
$hours = $diff->invert ? 24-$diff->h : $diff->h;
echo $hours; //5
Since you have 2 date pickers one for from time and another to time, the former will always be smaller than the latter. Hence when from time is larger than to time it means user has selected to from the next day. If we don't add a date for calculating difference, PHP will assume today's date by default. We can easily fix this by adding a condition to compare the times and prepend the dates accordingly. Below is the updated code.
<?php
$fromtime = '09:30 PM';
$totime = '02:00 AM';
$now = new \DateTime();
$today = $now->format('Y-m-d'); // Store current date
$now->add(new DateInterval('P1D')); // Add one day to current date to get next date
$nextDay = $now->format('Y-m-d'); // Store next date
if($fromtime > $totime) // If from time is bigger than to time, it means to is a next day
{
$fromdatetime = "$today $fromtime";
$todatetime = "$nextDay $totime";
}
else
{
$fromdatetime = "$today $fromtime";
$todatetime = "$today $totime";
}
$datetime1 = new \DateTime($fromdatetime);
$datetime2 = new \DateTime($todatetime);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%hh');
?>

Calculating time difference for fixed hour

I want to calculate the time difference from now (lets say 18:30:00) till this evening at 20pm.
$today = date('Y-m-d', time());
$remain = strtotime($today. " 00:00:00 + 20 hours") - time();
$remain = date('H:i:s', $remain);
I get a result which is one hour larger (02:30:00) than the actual result (01:30:00). I tried setting time zones but it's always the same result.
Using the DateTime object, you can do this easily:
$d1 = new DateTime('2015-04-23 18:30');
$d2 = new DateTime('2015-04-23 20:00');
$interval = $d2->diff($d1);
echo $interval->format('%H:%i hours');

How to get difference month from 2 date PHP?

i have date
$d1='2014-02-01';
$d2='2013-11-01';
i want if i minus $d2 - $d1 = i get difference of month = -3 and if $d1 - $d2 = 3 ,
Any one can help, sorry for my bad english
$d1= new DateTime('2014-02-01');
$d2= new DateTime('2013-11-01');
$diff = $d1->diff($d2);
echo $diff->format("%r%m");
Demo

how to check if a date is three days before today

Hey i would like to know if there is any script (php) that could check if a specified date three days before today.
say..
$d1 = date("Y-m-d", filemtime($testfile));
$d2 = date("Y-m-d");
now i would like to know how to compare this two dates to check if d1 is atleast 3days ago or before d2
any help would be gladly appreciated.
Why not to use DateTime object.
$d1 = new DateTime(date('Y-m-d',filemtime($testfile));
$d2 = new DateTime(date('Y-m-d'));
$interval = $d1->diff($d2);
$diff = $interval->format('%a');
if($diff>3){
}
else {
}
Assuming you wish to test whether the file was modified more than three days ago:
if (filemtime($testfile) < strtotime('-3 days')) {
// file modification time is more than three days ago
}
Just check it with timestamp:
if (time() - filemtime($testfile) >= 3 * 86400) {
// ...
}
use date("Y-m-d", strtotime("-3 day")); for specific date
you can also use
strtotime(date("Y-m-d", strtotime("-3 day")));
to convert it to integer before comparing a date string
well, stunned to see no one is using mktime() function,
it makes the job simple
for example your input date is :10/10/2012
mktime convert it to unix time stamp
$check_date=mktime(0,0,0,10,**10+3**,2012);
we can perform any operations weather +,-,*,/
use timestamp instead of date,
$d1 = filemtime($testfile);
$now = time();
if ($now - $d1 > 3600*24*3) {
..
}

Categories