I've viewed a few posts on this, but I'm still a bit confused on how it works.
I want to compare 2 times. The first time is the time NOW and the second time is a datetime coming from the database. I'm able to get the difference in days, months and years, but when I try to get the mins and seconds, the numbers do not seem correct.
Here is my code for getting the time in minutes and seconds:
$date1 = date('Y-m-d H:i:s');
$date2 = $blah['datetime']; //the variable here is in dateTime format coming from the database
$diff = abs(strtotime($date2) - strtotime($date1)); //Does this give the seconds?
$mins = floor($diff / 60);
So far minutes it's returning something like 560, even though I added that row (in the database to a table) a minute ago. Perhaps I'm misunderstanding something, or missing something. Let me know if you want me to clarify anything. Thanks!
This calculation is quite easy with PHP's DateTime and DateInterval classes.
$date1 = new \DateTime();
$date2 = \DateTime::createFromFormat('Y-m-d H:i:s', $blah['datetime']);
$diff = $date1->diff($date2); // $diff is an Instance of DateInterval
$mins = ($diff->days * 60 * 24) + ($diff->h * 60) + $diff->i;
Related
i try to make time difference with carbon
$dt = Carbon::parse('2018-07-15 00:00:00');
$now = Carbon::now('Asia/Dubai'); //set current time
$seconds = $now->diffInSeconds( $dt ); //difference turn into second
$days = $dt->diffInDays($dt->copy()->addSeconds($seconds));
$hours = $dt->diffInHours($dt->copy()->addSeconds($seconds)->subDays($days));
$minutes = $dt->diffInMinutes($dt->copy()->addSeconds($seconds)->subHours($hours));
$days result are 12 (its right).
$hours result are 8 (seems not right).
$minutes result are 17299 (clearly wrong).
how to get the result for example 12 day 5 hours 45 minutes
Actually functions like diffInSeconds give total difference in seconds that's why the number is so large,to get the minutes for the time difference right you can use -:
$minutes = ($now->minute - $dt->minute);
I have a date and time saved in a database, in the following format: 2016-04-03 12:54:11
Basically, this date and timestamp represents the exact date and time something was created. What I'm trying to do is display a second date and time, that is the exact number of days since the first timestamp.
So if the timestamp in the dataase was 2016-04-03 12:54:11 and todays date and time is 2016-04-04 12:54:11, it would display: Overdue by: 1 Day
So far I have:
<?PHP $dateCreated = mysql_result(mysql_query("SQL to stored date and time"),0);
$dateNow = time();
$dateDifference = abs(strtotime($dateCreated) - strtotime($dateNow));
$years = floor($dateDifference / (365*60*60*24));
$months = floor(($dateDifference - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($dateDifference - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); ?>
And then:
echo "<strong>Overdue by:</strong> $days Days.";
however, this code displays that 2 dates, only a day apart, as 14 days apart.
Help would be appreciated, cheers.
Try using DateTime objects. They'll make your life much easier.
The above could then be achieved with the following:
$date1 = new DateTime('2016-04-03 12:54:11');
$date2 = new DateTime('2016-04-04 12:54:11');
$diff = $date1->diff($date2);
The $diff variable will then be a DateInterval object, which has a days property to show the amount of days between the two dates. In this case 1, so you can do:
echo "Overdue by: " . $diff->days . " days.";
Which will output Overdue by: 1 days..
On a side-note: You should really not be using mysql_ functions anymore. They have been deprecated for years and are no longer part of the PHP core in the latest PHP version. So this code will not work on an up-to-date server. Also see: Why shouldn't I use mysql_* functions in PHP?
I think the best way to do it is using the Php DateTime class witch allow us to do it.
Try this:
$datetime1 = new DateTime("YOUR_DB_TIMESTAMP");
$datetime2 = new DateTime("today");
$difference = $datetime1->diff($datetime2);
echo difference->d;
Also, you can choose the way that you want to show the diference.
$diff->format('%R%a days')
Reference:
Example-> Finding the number of days between two dates
DateTime Doc -> http://php.net/manual/es/class.datetime.php
Regards!
I would use the DateTime object for things like this, because are really a very big help.
$dateCreatedObj = DateTime::createFromFormat('Y-m-d H:i:s', $dateCreated);
$dateNowObj = new DateTime();
$dateDifference = $dateCreatedObj->diff($dateNowObj);
echo $dateDifference->format('Overdue by: %a Day');
Please note that this does not handle timezones, multilingual and plural issues.
Diff function returns the difference between two DateTimeInterface objects.
You can try to use DateTime object :
<?PHP $dateCreated = mysql_result(mysql_query("SQL to stored date and time"),0);
$dateNow = new DateTime();
$dateOther = new DateTime($dateCreated);
$interval = $dateNow->diff($dateOther);
echo $interval->format('%R%a days');
I was previously using the php strtotime function to calculate the diff between two timestamps to check the duration of a given appointment. Now I need to include the dates as well as times as certain appointments can go for more than one day.
Previous code:
$duration = date('H:i',strtotime($row['scheduleTimeEnd']) - strtotime($row['scheduleTime']) - 3600)
New attempt with dates:
$duration = date('H:i',strtotime($row['scheduleDateEnd'].'T'.$row['scheduleTimeEnd'])
- strtotime($row['scheduleDate'].'T'.$row['scheduleTime']) - 3600)
Both pieces of code produce the same results. i.e. I have an appointment in my JSON feed which goes from 12th May 10:20 to the 18th May 17:20 and the duration values being returned by oth pieces of code below is 07:09.
Calculate the time difference -
$date1 = new DateTime('2015-05-17 17:20:00');
$date2 = new DateTime('2015-05-12 10:00:00');
$interval = $date1->diff($date2);
$days = $interval->days;
$hours = ($days * 24) + $interval->h;
echo "Difference : ". $hours .' : '.$interval->i;
Use DateTime Interface.
Output
Difference : 127 : 20
The problem is in the format of the date method you should updated like that :
$duration = date('d H:i' ,strtotime(
$row['scheduleDateEnd'].'T'.$row['scheduleTimeEnd'])
- strtotime($row['scheduleDate'].'T'.$row['scheduleTime']) - 3600)
By the format i mean d H:i ^^. ==> Doc
The future time is :2012-05-26 00:00:00
supposed there are three variable: $hour $minute $second
now, i want to using the future time subtract now time. then give the left hour to $hour,give the left minute to $minute,give the left second to $second.
i am sorry i am new of php, now i get stucked how to do the math operation ? thank you
A very good resource for dates and time..
http://www.php.net/manual/en/function.time.php
-there are samples here doing something similar.
Check the date_diff function. There's the exact solution to what you're asking there.
And here's the page (DateInterval::format) documenting how you can format the output.
$now = date_create();
// use "now" and necessary DateTimeZone in the arguments
$otherDate = date_create('2020-04-13');
$interval = date_diff($now, $futureDate);
echo $interval->format('%a days');
The following are the math operations for the difference in hours,minutes and seconds
$future_datetime = '2012-05-26 00:00:00';
$future = strtotime($future_datetime); //future datetime in seconds
$now_datetime = date('Y-m-d H:i:s');
$now = date('U'); //now datetime in seconds
//The math for calculating the difference in hours, minutes and seconds
$difference = $future - $now;
$second = 1;
$minute = 60 * $second;
$hour = 60 * $minute;
$difference_hours = floor($difference/$hour);
$remainder = $difference - ($difference_hours * $hour);
$difference_minutes = floor($remainder/$minute);
$remainder = $remainder - ($difference_minutes * $minute);
$difference_seconds = $remainder;
echo "The difference between $future_datetime and $now_datetime is $difference_hours hours, $difference_minutes minutes and $difference_seconds seconds";
I want to calculate the difference between two times, one of which is the current time, and the other is just in the format HH:MM, always in the future.
If I just subtract $futuretime from $now, it should, of course, be a positive number.
This works fine until...
If $now is in the afternoon or evening and $futuretime is, say, 7AM next morning, how can I force it to understand the the time is always going to be in the future?
(It's for working out the time of something that occurs about every half an hour during working hours, and then stops until the following morning)
Thanks in advance!
Simply add a whole day to the difference if it is negative. Assuming that $now and $futuretime are timestamps (stored in seconds since midnight), simply do the following:
$diff = $futuretime - $now;
if ($diff < 0)
$diff += 24 * 3600;
If they are in HH:MM format:
list($future_hours, $future_mins) = explode(":", $futuretime);
$futuretime = $future_hours * 60 + $future_mins;
list($now_hours, $now_mins) = explode(":", $now);
$now = $now_hours * 60 + $now_mins;
$diff = $futuretime - $now;
if ($diff < 0)
$diff += 24 * 60;
Of course the latter case returns the difference in minutes, while the former returns the difference in seconds.
Edit: as Andy noted below in the comments, this is not a good solution if you care about changes in DST. See his solution for a better approach.
If you're on PHP 5.3+, use PHP's DateTime:
$d1 = new DateTime('14:52:10');
$d2 = new DateTime('12:12:10');
$diff = $d1->diff( $d2 );
var_dump( $diff );
You can simply convert both dates to timestamp, do the calculations and convert it to required format, i.e. days, hours and minutes. it's quite simple.