Datediff round returns zero [duplicate] - php

This question already has answers here:
Finding the number of days between two dates
(34 answers)
Closed 3 months ago.
I'm trying to run a datediff. I essentially want to say the number of days between 1st November 2022 and 1st November 2022 is ONE day.
When I attempt this, $number_of_days returned is 0. Can someone explain why this is and how to resolve?
$end = "2022-11-01";
$start = "2022-11-01";
$datediff = ($end - $start) + 1; // tried to fix
echo $datediff;
echo '<hr>';
echo ($datediff / (60 * 60 * 24));
$number_of_days = round($datediff / (60 * 60 * 24));
echo '<hr>';
echo $number_of_days;

The dates you shown in the code are strings, they are not numerically "minorable". You need to convert them into a int of time first like this:
$end = strtotime("2022-11-01");
$start = strtotime("2022-11-01");
$datediff = (($end - $start)/60/60/24) + 1;
Why doesn't it work: If you try to subtract strings like this, PHP will auto-convert the strings into the boolean value true and then convert them into the integer 1. You divided it by (60 * 60 * 24) which results in a very small number 1.1574074074074E-5 which then be rounded into 0.

Your subtraction is using string values, not date values, so actually ends up as being 2022 - 2022, which equals zero...
(newer versions of PHP will complain "Notice: A non well formed numeric value encountered")
You could convert to instances of DateTime, and then determine the difference that way:
$end = "2022-11-01";
$start = "2022-11-01";
// convert to DateTime
$dtEnd = DateTime::createFromFormat('!Y-m-d', $end);
$dtStart = DateTime::createFromFormat('!Y-m-d', $start);
// get the difference in days
$days = $dtEnd->diff($dtStart)->format('%a') + 1;

Related

converting to DateTime from format y-z returns false

I have an old database with a column that contains expire dates, but not as dates but as integers that were generated like the following:
$year = date("y") * 365;
$day = date("z");
// $duration is an int representing an amount of days e. g. 30 or 60
$expire = $year + $day + $duration;
Now I try to convert these integers back to dates with the following code:
// $expire is the int that was selected from the database
$days = $expire % 365;
$year = ($expire - $days) / 365;
$date = DateTime::createFromFormat('y-d', $year . '-' . $days);
For the first int (7759, which gives 94 for $days and 21 for $year) it works, but for the second one (7769 -> 104 and 21) $date is false. I don't understand why that happens, I would think, that "104-21" is a just as valid formatted string as "94-21".
The task and the proposed solution contain some problems.
A number derived from a date with
$number = date("y") * 365 + date("z");
was created cannot be clearly assigned to the creation date. The date 2020-12-31 generates the number 7665. 2020 is a leap year with 366 days. However, the inverse transformation via date_create_from_format with the format 'y-z' returns the date 2021-01-01. A factor of at least 366 must be used (e.g. 1000) so that there are clear assignments.
When transforming back with date_create_from_format, the format '!y-z' should be used. Example for factor 1000:
$date = date_create_from_format('!y-z',(int)($number/1000).'-'.$number%1000);
That "!" in format should not be omitted. Without the exclamation mark, the time is not set to 00:00, but to the current server time. When calculating expiry times without "!", Deviations can occur up to 24 hours.

PHP Get last increment of five minutes [duplicate]

This question already has answers here:
Subtract time in PHP
(3 answers)
Closed 3 years ago.
I am looking to get the previous increment of five minutes from the current time...
Lets say that the current time is 12:07pm UTC
I want to put into a variable 12:05pm UTC
What would be an easy way of going about this?
You can do this with the DateTime class (https://3v4l.org/7aqMH):
<?php
$date = new DateTime('12:07 UTC');
$minutes = (int) $date->format('i');
$rounded = round($minutes / 5) * 5;
$date->setTime($date->format('H'), $rounded, $date->format('s'));
or more concisely:
<?php
$date = new DateTime('12:07 UTC');
$date->setTime(
$date->format('H'),
round($date->format('i') / 5) * 5,
$date->format('s')
);
There's nothing built in that allows you to retrieve 'increments' however you can calculate it with minimal code. The use of modulo here allows you to figure out how far past the most recent 5 minute mark is. It will never be greater than 5 minutes (300 seconds) and can always be subtracted safely to take you back to the time you want.
$now = time();
echo $now . PHP_EOL;
$five_minutes = 60*5; // 300
$offset = $now % $five_minutes;
$five_block = $now - $offset;
echo date('Y-m-d H:i:s', $five_block);
First you will want to extract the minutes from their stored variable. Then mathematically this is simple by applying division and the floor function. To do this you can first divide by five using intdiv(numerator, denominator) which will remove any trailing decimal points and then multiply by five again to get your desired value at an increment of five.
Get the current time using time() :
$min = 300
$currentTime = time();
$mod = $currentTime % $min;
$res = $currentTime - $mod;
finalResult = date('Y-m-d H:i:s', $res);

Return the difference between two (dates and time ) PHP

i tried most of what is available on stack overflow but none seem to work.
any way i am trying to compare two (date and time formats). and calculate whether their difference is within 5 seconds of each other
the first date is the current date:
$today = date("Y-m-d H:i:s");
the second date is taken from mysql database:
$result = mysql_query("SELECT * FROM BUS_DATA where BusRegID = 'bus'") or die(mysql_error());
$row = mysql_fetch_array($result);
$update_date = $row["update_date"];
the answer should be segmented into years , month , days , hours , minutes ,and seconds portions.
I am running PHP Version 5.3.3
Edit: most answers give result in time frame only , I want to check whether the date matches , then compare if the time of the day is within 5 seconds , than you guys in advance :)
Try this
function getTimes($t1, $t2)
{
$timeFirst = strtotime($t1);
$timeSecond = strtotime($t2);
$differenceInSeconds = $timeSecond - $timeFirst;
$h=0;
$m = floor($differenceInSeconds / 60);
$s = $differenceInSeconds % 60;
if ($m>=60)
{
$h = floor($m / 60);
$m = $m % 60;
}
$tim = $h.':'.$m.':'.$s;
return $tim;
}
it will return difference time in hours:min:sec
use strtotime, it's understands almost any date formats:
$timeDiff = abs(strtotime($today) - strtotime($update_date));
this gives you the difference between dates in seconds.
If you want to know whether it's within 5 seconds then use Timestamps, makes it into a simple int calculation.
$now = time();
$test = strtotime($update_date);
if($now - $test > 5) {
//NOT WITHIN 5 SECONDS
}

date format in PHP date function [duplicate]

This question already has answers here:
Calculating the difference between two times using php, and then adding it to a total of time type
(2 answers)
Closed 9 years ago.
Hi I have values stored in MSSQL database as time(7)
job_start
job_end
I am trying to work out the difference between these two times using php, i have the folowing code
$start = $model->job_start;
$end = $model->job_end;
$diff = date( "h:i:s", strtotime($end) - strtotime($start) ) ;
echo $diff ;
However the output is
03:06:00
Rather than
00:06:00
By the way the difference is 6 minutes (360 seconds), can anyone help get this in the right format so i can save it ?
This question has been marked as a duplicate, however it is a different question as this addresses a specific timezone question when using the date function. And has been answered as such.
EDIT
The code i have marked answered the question i asked however I am trying to add an extra calculation as follows
$start = $model->job_start;
$end = $model->job_end;
$total = $model->customer->total_time;
//adding time difference to total time used for that customer
$dt = strtotime($total) + strtotime($end) - strtotime($start);
$hours = floor($dt / 3600);
$minutes = floor($dt / 60) - $hours * 60;
$seconds = $dt - $hours * 3600 - $minutes * 60;
// Padded values
$hours = str_pad($hours, 2, STR_PAD_LEFT, '0');
$minutes = str_pad($minutes, 2, STR_PAD_LEFT, '0');
$seconds = str_pad($seconds, 2, STR_PAD_LEFT, '0');
$output = "{$hours}:{$minutes}:{$seconds}" ;
//display
echo '<br> Start time : '. $start;
echo '<br> End time : '. $end;
echo '<br> total time + time difference : '. $output;
echo '<br> Total time for Customer : '. CHtml::encode($model->customer->total_time);
I am trying to add the difference between the total times to a total time variable
However when output is echoed i get this display
Start time : 11:45:00.0000000
End time : 12:45:00.0000000
total time + time difference : 382015:00:00
Total time for Customer : 09:00:00.0000000
Note that the total time + time difference has extra digits before it , its probably a simple mistake on my part but I can't see it , any help would be appreciated
Why not do this in the database
SELECT TIMESTAMPDIFF(SECOND, job_start, job_end);
Its faster and it is clearer for others to see what you are trying to do.
First of all, date gives date since Unix epoch (1970-01-01 00:00:00) so the odd three hour difference you see there is your timezone. You need to parse the hours, minutes and seconds separately.
<?php
$end = '2013-07-30 23:27:00';
$start = '2013-07-30 21:23:56';
$dt = strtotime($end) - strtotime($start);
$hours = floor($dt / 3600);
$minutes = floor($dt / 60) - $hours * 60;
$seconds = $dt - $hours * 3600 - $minutes * 60;
// Padded values
$hours = str_pad($hours, 2, STR_PAD_LEFT, '0');
$minutes = str_pad($minutes, 2, STR_PAD_LEFT, '0');
$seconds = str_pad($seconds, 2, STR_PAD_LEFT, '0');
$output = "{$hours}:{$minutes}:{$seconds}";

Get interval seconds between two datetime in PHP?

2009-10-05 18:11:08
2009-10-05 18:07:13
This should generate 235,how to do it ?
With DateTime objects, you can do it like this:
$date = new DateTime( '2009-10-05 18:07:13' );
$date2 = new DateTime( '2009-10-05 18:11:08' );
$diffInSeconds = $date2->getTimestamp() - $date->getTimestamp();
You can use strtotime() to do that:
$diff = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13')
A similar approach is possible with DateTime objects, e.g.
$date = new DateTime( '2009-10-05 18:07:13' );
$date2 = new DateTime( '2009-10-05 18:11:08' );
$diff = $date2->getTimestamp() - $date->getTimestamp();
PHP Date Time reference is helpful for things like this: PHP Date Time Functions
strtotime() is probably the best way.
$seconds = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13')
For those worrying about the limitations of using timestamps (i.e. using dates before 1970 and beyond 2038), you can simply calculate the difference in seconds like so:
$start = new DateTime('2009-10-05 18:11:08');
$end = new DateTime('2009-10-05 18:07:13');
$diff = $end->diff($start);
$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->h * 60 * 60;
$minsInSecs = $diff->i * 60;
$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->s;
echo $seconds; // output: 235
Wrote a blog post for those interested in reading more.
Because of unix epoch limitations, you could have problems compairing dates before 1970 and after 2038. I choose to loose precision (=don't look at the single second) but avoid to pass trough unix epoch conversions (getTimestamp). It depends on what you are doing to do...
In my case, using 365 instead (12*30) and "30" as mean month lenght, reduced the error in an usable output.
function DateIntervalToSec($start,$end){ // as datetime object returns difference in seconds
$diff = $end->diff($start);
$diff_sec = $diff->format('%r').( // prepend the sign - if negative, change it to R if you want the +, too
($diff->s)+ // seconds (no errors)
(60*($diff->i))+ // minutes (no errors)
(60*60*($diff->h))+ // hours (no errors)
(24*60*60*($diff->d))+ // days (no errors)
(30*24*60*60*($diff->m))+ // months (???)
(365*24*60*60*($diff->y)) // years (???)
);
return $diff_sec;
}
Note that the error could be 0, if "mean" quantities are intended for diff. The PHP docs don't speaks about this...
In a bad case, error could be:
0 seconds if diff is applied to time gaps < 1 month
0 to 3 days if diff is applied to time gaps > 1 month
0 to 14 days if diff is applied to time gaps > 1 year
I prefer to suppose that somebody decided to consider "m" as 30 days and "y" as 365, charging "d" with the difference when "diff" walk trough non-30-days months...
If somebody knows something more about this and can provide official documentation, is welcome!
strtotime("2009-10-05 18:11:08") - strtotime("2009-10-05 18:07:13")
The solution proposed by #designcise is wrong when "end date" is before "start date".
Here is the corrected calculation
$diff = $start->diff($end);
$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->format('%r%h') * 60 * 60;
$minsInSecs = $diff->format('%r%i') * 60;
$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->format('%r%s');
A simple and exact solution (exemplifying Nilz11's comment):
$hiDate = new DateTime("2310-05-22 08:33:26");
$loDate = new DateTime("1910-11-03 13:00:01");
$diff = $hiDate->diff($loDate);
$secs = ((($diff->format("%a") * 24) + $diff->format("%H")) * 60 +
$diff->format("%i")) * 60 + $diff->format("%s");

Categories