3 days is only 2 days and 11 hours away? - php

This is a follow up to this question: Counting down days not showing the right number of days
I'm still confused about dates and times.
Setting the start and end times:
// start date: set the time of when you click the link
$startTime = strtotime('now');
$plantStart = date('M d, Y h:i:s', $startTime);
// end date: 3 days from the time of when you click the link
$date = strtotime("+3 day", $startTime);
$plantEnd = date('M d, Y h:i:s', $date);
This gives me:
Mar 17, 2014 07:33:45 (start)
Mar 20, 2014 07:33:45 (end)
Now, the problem.. when I do this:
// show how many days/hours till $plantEnd date
$d = new DateTime($plantEnd);
$daysHours = $d->diff(new DateTime())->format('%d Days, %H Hours');
echo $daysHours;
The result is always something like: 2 Days, 11 Hours its never 3 days 0 hours or 2 days 23 hours.. Is it still just getting the time till 0:00:00 on the 3rd day instead of to the exact minute of the time?

As Yohann Tilotti mention in the comments, the issue it that new DateTime() is never initialized in the diff() function.
What you probably meant was: $d->diff(new DateTime($plantStart)).
You can see a running example here: http://ideone.com/FU8akb

Like I commented, stick to one method of dates. The preferred method being DateTime:
$plantStart = new DateTime('now');
echo $plantStart->format('Y-m-d H:i:s');
// Output: 2014-03-17 12:56:00
$plantEnd = new DateTime('now + 3 days');
echo $plantEnd->format('Y-m-d H:i:s');
// Output: 2014-03-20 12:56:00
$daysHours = $plantEnd->diff(new DateTime())->format('%d Days, %H Hours');
echo $daysHours;
// Output: 3 Days, 00 Hours

Related

How to correctly calculate time remaining from php date time

The expiry date is in unix timestamp approx 30th sept 2020 6AM
$expiry_date_time = 160142766; //30 sept 2020 6AM
$dt1 = new DateTime();
$dt1->setTimestamp($expiry_date_time);
$now = new DateTime();
$i = $now->diff($dt1);
$time_remaining = $i->format('%y years %m months %a days %h hours %i minutes');
echo $time_remaining;
Output today when i ran the code (11th OCT 2020)
0 years 0 months 11 days 7 hours 19 minutes
This code doesn't give incorrect result but it cannot differentiate between expired and not expired, like in the above case the subscription had expired it gives the output 11 days which is not entirely incorrect because it has been 11 days since its expired if you calculate but shouldn't it be Negative 11 days ?
If I make the expiry date to two days in the future it will correctly calculate and output 2 days, xx hours and xx minutes.
How to make it differentiate between expired and not expired ?
DateInterval has an invert flag for this very purpose:
invert
Is 1 if the interval represents a negative time period and 0 otherwise.
$expiry_date_time = 160142766; //30 sept 2020 6AM
$dt1 = new DateTime();
$dt1->setTimestamp($expiry_date_time);
$now = new DateTime();
// What you're doing right now
$i = $now->diff($dt1);
var_dump($i->invert); // int(1)
// If you're doing it the other way around
$i = $dt1->diff($now);
var_dump($i->invert); // int(0)
Demo
$expiry_date_time = 160142766; //30 sept 2020 6AM
$dt1 = new DateTime();
$dt1->setTimestamp($expiry_date_time);
$now = new DateTime();
$i = $now->diff($dt1);
$time_remaining = $i->format('%y years %m months %a days %h hours %i minutes');
if($expiry_date_time - $now()->getTimestamp() < 0) {
$time_remaining = "expired $time_remaining ago";
}
echo $time_remaining;
This will add some text to the text if it is in the past, to make sure you know if it is expired or not yet.

get last date in month error

I have the following code which gets the date parsed, the subtracts 1 month. This works perfectly.
$date = '22-05-2016';
print(date("Y-m-d 23:59:59", strtotime($date.' -1 months')));
// outputs 2016-04-22 23:59:59
There are times where I need to force the date to month end. For this I use Y-m-t instead of Y-m-d Which works perfectly.
$date = '22-05-2016';
print(date("Y-m-t 23:59:59", strtotime($date.' -1 months')));
// outputs 2016-04-30 23:59:59
The problem comes when the date that is parsed is actually the last day of that month. It then flips to end of the next month.
$date = '31-05-2016';
print(date("Y-m-t 23:59:59", strtotime($date.' -1 months')));
Actual Output 2016-05-31 23:59:59 (hasn't removed 1 month)
Desired Output 2016-04-30 23:59:59
EDIT: Fiddle example http://ideone.com/0fqlor
Try:
$date = '31-05-2016';
print(date("Y-m-d 23:59:59", strtotime($date.' last day of last month')));
and dig into strtotime possibilities ;)
Take a look here: http://php.net/manual/en/datetime.formats.relative.php
Last Note: -1 month only gets 30 days back in time. Therefore it will not work allways. Some kind of PHP stuff, i think ;)
strtotime is your friend. The last day of any "given" month can be retrieved using the verbal String last day of May 2015 - so, for easy input (guess you have a date-picker not a month-picker), convert the selected date to its month expression first:
date_default_timezone_set('Europe/London');
$to = '31-05-2016';
$month = date("M Y", strtotime($to));
$strtotime_expression = "last day of " . $month;
echo $strtotime_expression.": <br />";
print(date("Y-m-t 23:59:59", strtotime($strtotime_expression)));
http://ideone.com/YvjVeP

php date addition skipping days

I have a date, and need to add 24 Months (and not 2 Year) to it. This is what I tried:
strtotime("+24 months", $mydate);
If my date is, 20th Dec 2013 then the computed date is coming as 10th Dec 2015, whereas my expected date was 20th Dec 2015.
I know, what is going behind the scene:
2 Year: 365 days x 2 = 730 days
24 Months: 24 x 30days = 720 days
This gives me the missing 10 days. But how to over come this issue.
In Java we have Calendar class, which takes care of such calculations. However, I din't find anything here.
Can this issue be resolved.? Or I need to handle it manually?
You should always use the DateTime() class for anything like that.
i.e
$date = new DateTime("UTC");
//get date in 24months time:
$date->add(new DateInterval("P24M"));
//output date:
echo $date->format("d/m/Y H:i:s");
By using the DateTime and DateInterval classes, you can be sure that it will account of leap years and other such irregularities in dates.
See more at: http://php.net/manual/en/class.datetime.php
I hope this helps.
$mydate = "2014-10-01";
echo date('d-m-Y',strtotime("+24 months", strtotime($mydate)));
DateTime should work perfectly here:
$date = new DateTime("20th Dec 2013");
echo $date->format("d-m-Y");
$date->add(new DateInterval('P24M'));
echo $date->format("d-m-Y");
Output:
20-12-2013
20-12-2015
Demo
Sidenote:
I couldn't reproduce your error with:
echo date("d-m-Y", strtotime("+24 months", $mydate = strtotime("2013-12-20")));
See:
http://3v4l.org/HURAt

Take current datetime and make 2 datetime variables? (6AM - 5:59AM)

I'm trying to make an events page and I want to create 2 datetime variables. They would take the current time, and create one variable at 06:00 am, and one at 05:59 am.
The issue I'm having though is with the calculations.
If a person is visiting the page on March 17, 11PM - then var1 would be March 17 06:00AM, and var 2 March 18 05:59AM.
However if a person is viewing the page on March 18 01:00 AM, then var 1 would still be March 17 06:00AM, the same goes for var2.
How would I take the below $date variable, and do the calculations for the other 2 variables?
date_default_timezone_set('America/New_York');
$date = date('Y-m-d H:i:s', time());
You can simply query the current hour to see if it's less than 6; if it is, then the start of the current logical day (based on your rules) was yesterday, 6am; otherwise it was today, 6am. Given this, strtotime can trivially get you the "start" time and adding a day to that gives you the "end" time.
date_default_timezone_set('America/New_York');
$currentHour = date('H');
if ($currentHour < 6) {
// logical day started yesterday
$start = strtotime('yesterday 06:00');
$end = strtotime('today 05:59:59');
}
else {
// logical day started today
$start = strtotime('today 06:00');
$end = strtotime('tomorrow 05:59:59');
}
echo "The current logical day started on ".date('Y-m-d H:i:s', $start);
echo " and it ends on ".date('Y-m-d H:i:s', $end);
The method for chopping the date up could be improved, but the principle works...
<?php
date_default_timezone_set('America/New_York');
$date = date('Y-m-d H:i:s', time());
// get adjusted date which subtracts 6 hours
$date_adjusted = date('Y-m-d H:i:s', time() - 60 * 60 * 6);
// chop off the time (so we are always left with the correct date now)
$date_adjusted_date = preg_split("/ /",$date_adjusted);
// Add the time element (in this case 6 AM)
$correct_date = date('Y-m-d H:i:s', strtotime($date_adjusted_date[0]."T06:00:00"));
// check the result
echo $correct_date;
?>

PHP, need to subtract 12 hours and 30 minutes from a DateTime

I have a PHP DateTime variable.
How can I reduce or subtract 12hours and 30 minutes from this date in at PHP runtime?
Subtract 12 Hours and 30 minutes from a DateTime in PHP:
$date = new DateTime();
$tosub = new DateInterval('PT12H30M');
$date->sub($tosub);
The P stands for Period. The T stands for Timespan.
See DateTime, DateTime::sub, and DateInterval in the PHP manual. You'll have to set the DateTime to the appropriate date and time, of course.
Try with:
$date = new DateTime('Sat, 30 Apr 2011 05:00:00 -0400');
echo $date->format('Y-m-d H:i:s') . "\n";
$date->sub(new DateInterval('PT12H30M'));
echo $date->format('Y-m-d H:i:s') . "\n";
//Result
2011-04-30 05:00:00
2011-04-29 16:30:00
Try strtotime() function:
$source_timestamp=strtotime("Sat, 30 Apr 2011 05:00:00 -0400");
$new_timestamp=strtotime("-12 hour 30 minute", $source_timestamp);
print date('r', $new_timestamp);
Maybe it will be useful for some cases
$date = new DateTime();
$date->modify('-12 hours -30 minutes');
echo $date->format('H:i:s');
try using this instead
//set timezone
date_default_timezone_set('GMT');
//set an date and time to work with
$start = '2014-06-01 14:00:00';
//display the converted time
echo date('Y-m-d H:i',strtotime('+1 hour +20 minutes',strtotime($start)));
If you are not so familiar with the spec of DateInterval like PT12H30M you can proceed with more human readable way using DateInterval::createFromDateString as follows :
$date = new DateTime();
$interval = DateInterval::createFromDateString('12 hour 30 minute');
$date->sub($interval);
Or with direct interval in sub function like below :
$date = new DateTime();
$date->sub(DateInterval::createFromDateString('12 hour 30 minute'));
Store it in a DateTime object and then use the DateTime::sub method to subtract the timespan.
I used in one line, for 12 hours only, and just as an hour display
$date = new DateTime(); $date->modify('-12 hours'); echo $date->format('H')-0;
I used the -0 since sometimes it put a 0 in front of the digit unless I done that, strange.
Here is detailed description of date function,
Using simply strtotime
echo date("Y-m-d H:i:s",strtotime("-12 hour -30 minutes"));
Using DateTime class
$date = new DateTime("-12 hour -30 minutes");
echo $date->format("Y-m-d H:i:s");

Categories