php date_diff function returns 0 - php

I'm trying to get the difference between a date and current date but always returns 0.
$start_date = get_field('start_date', false, false); // 2021-12-15 09:00:00
$start_date = new DateTime($start_date);
$date_now = new DateTime();
if ($date_now > $start_date){
$diff = date_diff($date_now, $start_date);
}
echo $diff->format("%y Year %m Month %d Day %h Hours %i Minute %s Seconds");

The issue seems to be that $date_now is less than $start_date, so the code inside of the if block never runs. As such $diff is undefined. This should be throwing an error, which might have helped you suss this out - but sometimes error reporting is turned off. You might want to set up a local testing environment where error reporting is enabled, I'd bet you get to the bottom of this in no time. :-)
What you might be wanting is something closer to this:
$start_date = get_field('start_date', false, false); // 2021-12-15 09:00:00
$start_date = new DateTime($start_date);
$date_now = new DateTime();
$diff = date_diff($date_now, $start_date);
$time_from_str = $diff->invert ? "ago" : "until"
echo $diff->format("%y Year %m Month %d Day %h Hours %i Minute %s Seconds")
. " "
. $time_from_str;
This always gets the interval of time, but adds some context for the end user to know if the time is in the past or the future.
Or, if you want to hard-stop at the start_date (which is implied by the id statement), you could do:
$start_date = get_field('start_date', false, false); // 2021-12-15 09:00:00
$start_date = new DateTime($start_date);
$date_now = new DateTime();
if($date_now > $start_date) {
$diff = date_diff($date_now, $start_date);
} else {
$diff = new DateInterval("P0Y"); // an empty time interval, just so $diff is still defined
}
echo $diff->format("%y Year %m Month %d Day %h Hours %i Minute %s Seconds");
Hope that's helpful. Good luck!

Related

Get difference between date returns zero

I have a date time in 'Y-m-d H:i:s', and i tried to substract the now date with the defined date +1 day to get remaining time in hours, minutes and seconds:
$time = '2017-10-05 14:54:03';
$now = date('Y-m-d H:i:s');
$endTransaction = date('Y-m-d H:i:s', strtotime($time. ' + 1 day'));
$dteDiff = $endTransaction - $now;
echo $dteDiff;
but i always get 0 as the result
You are doing it wrong. The date function returns string so PHP is not able to compare anything. Try with the DateTime class instead. Its diff method returns the DateInterval object with some public properties, like the days property among others, which is the positive integer number (rounded down) of days between two dates:
$now = new \DateTime();
$endTransaction = (new \DateTime('2017-12-05 14:54:03'))->modify('+1 day');
$diff = $endTransaction->diff($now);
printf(
'Difference in days: %d, hours: %d, minutes: %d, seconds: %d',
$diff->days,
$diff->h,
$diff->m,
$diff->s
);
You probably need to use this date_diff
$time = '2017-10-05 14:54:03';
$now = date_create(date('Y-m-d H:i:s'));
$endTransaction = date_create(date('Y-m-d H:i:s', strtotime($time. ' + 1 day')));
$dteDiff = date_diff($now, $endTransaction);
$date = new DateTime($dteDiff);
$result = $date->format('Y-m-d H:i:s');
According to above mentioned description please try executing following code snippet as a solution to it.
$time = '2017-10-05 14:54:03';
$now = strtotime(date('Y-m-d H:i:s'));
$endTransaction = strtotime(date('Y-m-d H:i:s', strtotime($time. ' + 1 day')));
$dteDiff = ($endTransaction - $now)/(24*60*60);
echo round($dteDiff);
$endTransaction and $now are strings.
$time = '2017-10-05 14:54:03';
$now = date('Y-m-d H:i:s');
$endTransaction = date('Y-m-d H:i:s', strtotime($time. ' + 1 day'));
echo($endTransaction."\n");
echo($now."\n");
It prints:
2017-10-06 14:54:03
2017-10-05 11:45:39
The subtraction is not a valid operation for strings. It can handle only numbers. The strings above are converted to numbers. The conversion uses only the leftmost digits present in the string, until it reaches the first character that is not a digit.
Both strings above produce 2017 when they are converted to numbers and their difference is, of course, 0.
The easiest way to work with dates in PHP is to use the DateTime and its related classes.
// Convert the input string to a DateTime object
$then = new DateTime('2017-10-05 14:54:03');
// Add 1 day
$then->add(new DateInterval('P1D'));
// Get the current date and time
$now = new DateTime('now');
// Compute the difference; it is a DateInterval object
$diff = $now->diff($then);
// Display the dates and the difference
echo('Then: '.$then->format("Y-m-d H:i:s\n"));
echo('Now : '.$now->format("Y-m-d H:i:s\n"));
echo('Remaining: '.$diff->format("%R%a days, %h hours, %i minutes, %s seconds.\n"));
The output:
Then: 2017-10-06 14:54:03
Now : 2017-10-05 12:36:25
Remaining: +1 days, 2 hours, 17 minutes, 38 seconds.

days, hours, and minutes remaining in php

I have this timestamp from the database 1496592689
the problem is I don't know how to get the remaining days, hours and minutes
but I have this code bellow
this is my variable from where the timestamp stored $db_user_timestamp
and now I have this current time now $timenow = time();
I tried to calculate it with
$remainingtime = $db_user_timestamp - $timenow;
But I don't know how to put it in the days, hours and minutes.
Thanks in advance for helping me :)
Always use DateTime
$create_time = "1496592689";
$current_time = time();
$dtCurrent = DateTime::createFromFormat('U', $current_time);
$dtCreate = DateTime::createFromFormat('U', $create_time);
$diff = $dtCurrent->diff($dtCreate);
$interval = $diff->format("%y years %m months %d days %h hours %i minutes %s seconds");
$interval = preg_replace('/(^0| 0) (years|months|days|hours|minutes|seconds)/', '', $interval);
echo $interval;
result
6 months 30 days 5 hours 52 minutes
If your PHP version is 5.3 or latest, you should check
http://php.net/manual/en/class.dateinterval.php
and
http://php.net/manual/en/datetime.diff.php
$datetime1 = new DateTime(date('Y-m-d H:i:s', $db_user_timestamp));
$datetime2 = new DateTime(date('Y-m-d H:i:s'));
$interval = $datetime1->diff($datetime2);
echo $interval->format('%y years %m months %d days %h hours %m minutes %s seconds');
<?php
$db_user_timestamp = 1496592689;
$difference = $db_user_timestamp - time();
echo "Day : ".$day = date('d',$difference);
echo "<br>Hour : ".$hour = date('H',$difference);
echo "<br>Minute : ".$minute = date('i',$difference);
?>
Using date('M/d/Y H:i:s', $theTimestamp); will give you date in day, month, year, hour, minute, seconds in the order you want (change 'M/d/Y H:i:s' to your string depending on http://php.net/manual/en/function.date.php)

Find the difference between two time stamps

$diff = strtotime(12:00:00) - strtotime(5:01:29);
echo date('H:i:s', $diff);
result is 12:01:29
Trying to get the result of 5 hrs 1 min 29 sec
I prefer to use the DateTime class for time comparison / addition / subtraction:
$dt1 = new DateTime();
$dt1->setTimestamp(strtotime('12:00:00am'));
$dt2 = new DateTime();
$dt2->setTimestamp(strtotime('5:01:29am'));
$interval = $dt1->diff($dt2);
echo $interval->format('%h hrs %i min %s sec');
Edit: with the format you gave in strtotime it was thinking 5:01am to 12pm - so it was giving a very different answer than what you wanted, so you need to specify am/pm

Formatting php timedifference based on days

I'm calculating a timedifference with this bit of php and formatting it in days, hours and minutes.
// Compares expires_at with the current time
$now = new DateTime();
$future_date = new DateTime($contest->expires_at);
$interval = $future_date->diff($now);
$enddate = $interval->format("%a days, %h hours, %i minutes");
// if current time is higher than expiration date set contest to finished.
if($now > $future_date) {
$enddate = 'Date ended';
}
Now I want to have the format to only display the total amount of days when it's over a day(24 hours) and start to format in hours and minutes when it's less than a day(24 hours). So it will format to hours and minutes starting from like 23 hours 59 minutes, you get the idea hopefully.
Can anyone tell me how does it done the easiest?
Do it like this:
// Compares expires_at with the current time
$now = new DateTime();
$future_date = new DateTime($contest->expires_at);
$interval = $future_date->diff($now);
if ($now > $future_date) {
// if current time is higher than expiration date set contest to finished.
$enddate = 'Date ended';
} else if ($interval >= new DateInterval("P1D")) {
$enddate = $interval->format("%a days, %h hours, %i minutes");
} else {
$enddate = $interval->format("%a days, %h hours, %i minutes");
}

Getting days from DateTime() above 30/31 so it doesn't carry over to months

I'm calculating the difference between 2 dates using DateTime() and it's working fine. The problem is that I want to have the days format be able to go above a full month so 30/31 or higher.
$now = new DateTime();
$future_date = new DateTime($contest->expires_at);
$interval = $future_date->diff($now);
$enddate = $interval->format("%m month, %d days, %h hours, %i minutes");
The current problem with this is that when I don't display the months, the days can only go up to 30/31 and anything over that will be carried over to make a new month resetting the days count with the leftover days.
I want to be able to display 42 days when the difference is 6 weeks with this kind of format:
$enddate = $interval->format("%d days, %h hours, %i minutes");
Is there a quick fix for this or do I need to manually convert the timestamp to seconds and use my own function with modulus operators for this?
You can try:
$enddate = $interval->format("%a days, %h hours, %i minutes");
See the DateInterval::format in the manual.
NOTE
Take care of the bug if you're working on windows.
This should solve your porblem:
$now = new DateTime();
$future_date = new DateTime();
// a period of 2 months
$addPeriod = new DateInterval('P2M');
// adding the period
$future_date->add($addPeriod);
// get the differnce
$interval = $future_date->diff($now);
echo($interval->days) . ' days';
For today: echo returns '61 days'
// EDIT
To avoid running into the dataInterval-Bug you can use:
$now = new DateTime();
$future_date = new DateTime();
// a period of 2 months
$addPeriod = new DateInterval('P2M');
// adding the period
$future_date->add($addPeriod);
// get the difference in second
$diffTimestamp = $future_date->getTimestamp() - $now->getTimestamp();
// convert to days
// 1 day = 86.400 seconds
$diffDays = $diffTimestamp/86400;
echo(floor($diffDays)) . ' days';
Update my php version since this is a bug in my old and it works perfectly now.
How to get aggregate days from PHP's DateTime::diff?

Categories