Hướng dẫn calculate time duration php

How can I calculate time duration considering the datestamp in PHP? the date format I used in between dates is "Y-m-d H:i:s",

My working code can only compute the duration between time without considering the date.

below is my code:

$assigned_time = "2012-05-21 22:02:00";
$completed_time= "2012-05-22 05:02:00";   

function hmsDiff ($assigned_time, $completed_time) {
    $assigned_seconds = hmsToSeconds($assigned_time);
    $completed_seconds = hmsToSeconds($completed_time);

    $remaining_seconds = $assigned_seconds - $completed_seconds;

    return secondsToHMS($remaining_seconds);
}
function hmsToSeconds ($hms) {
    $total_seconds = 0;
    list($hours, $minutes, $seconds) = explode(":", $hms);
    $total_seconds += $hours * 60 * 60;
    $total_seconds += $minutes * 60;
    $total_seconds += $seconds;

    return $total_seconds;
}

 function secondsToHMS ($seconds) {
    $minutes = (int)($seconds / 60); 
    $seconds = $seconds % 60;
    $hours = (int)($minutes / 60); 
    $minutes = $minutes % 60;

    return  sprintf("%02d", abs($hours)) . ":" . 
        sprintf("%02d", abs($minutes)) . ":" . 
        sprintf("%02d", abs($seconds));

 }

asked May 23, 2012 at 2:07

0

The DateTime has a "diff" method which returns an Interval object. The interval object has a method "format" which allows you to customize the output.

#!/usr/bin/env php
<?php

$assigned_time = "2012-05-21 22:02:00";
$completed_time= "2012-05-22 05:02:00";   

$d1 = new DateTime($assigned_time);
$d2 = new DateTime($completed_time);
$interval = $d2->diff($d1);

echo $interval->format('%d days, %H hours, %I minutes, %S seconds');

NOTE: If you are not using 5.3.0+, there is a good answer here: https://stackoverflow.com/a/676828/128346.

answered May 23, 2012 at 2:23

Wil Moore IIIWil Moore III

6,7933 gold badges35 silver badges46 bronze badges

2

Not completely knowing what you want, what about something like:

// prevents php error
date_default_timezone_set ( 'US/Eastern' );
// convert to time in seconds
$assigned_seconds = strtotime ( $assigned_time );
$completed_seconds = strtotime ( $completed_time );

$duration = $completed_seconds - $assigned_seconds;

// j gives days
$time = date ( 'j g:i:s', $duration );

answered May 23, 2012 at 2:14

DavidDavid

3,2551 gold badge35 silver badges53 bronze badges

Possible Duplicates:
Number of seconds from now() to Sunday midnight
Calculates difference between two dates in PHP

Nội dung chính

  • Comparing Timestamps to Get Number of Seconds Between Two Dates
  • Calculating Number of Seconds Between Two Dates
  • How will you get the difference between 2 datetime values in seconds in php?
  • How do you calculate seconds between two times?
  • How can I get minutes between two dates in php?
  • How can I compare two time in php?

Hello All,

In my project, I need to calculate the difference in seconds between two dates:

For Example :

$firstDay = "2011-05-12 18:20:20";
$secondDay = "2011-05-13 18:20:20";

Then I should get 86400 Seconds That is 24 hours.

Similarly For

$firstDay = "2011-05-13 11:59:20";
$secondDay = "2011-05-13 12:00:20";

It should return 60 Seconds.

I read lots of questions in the stackoverflow But they only deals with the difference between 2 minute fields like 11:50:01 and 12:10:57

asked May 13, 2011 at 7:07

1

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Gordon

307k72 gold badges526 silver badges551 bronze badges

answered May 13, 2011 at 7:13

JordoniasJordonias

5,6682 gold badges20 silver badges32 bronze badges

0

By default there's no method available on the DateTime or DateInterval class to get the difference between two DateTime objects in seconds. Therefore, you can either get the difference of the timestamps of the two dates or calculate the number of seconds yourself:

Comparing Timestamps to Get Number of Seconds Between Two Dates

We can simply compare timestamps of two dates to get the difference in seconds. For example:

$start = new DateTime('2011-12-31 00:00:00');
$end = new DateTime('2021-01-01 00:00:00');

echo $end->getTimestamp() - $start->getTimestamp(); // output: 284169600

Please note that comparing timestamps could lead to problems with dates before 1970 and after 2038.

Calculating Number of Seconds Between Two Dates

You can calculate the number of seconds between the two dates in the following way:

$start = new DateTime('2011-12-31 00:00:00');
$end = new DateTime('2021-01-01 00:00:00');
$diff = $start->diff($end);

$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: 284169600

The calculation works in the following way:

  • Using the %r formatting character, adds the minus sign when the result is negative;
  • Using the %a formatting character gives us the total number of days between two dates;
  • Using the %r%a format together, we can get the negative/positive number of days. Using that, we can convert the number of days into seconds by multiplying it with hours in a day, minutes in an hour, and seconds in a minute (i.e. days * 24 * 60 * 60);
  • The calculation in the last step does not take into account the hours, minutes and seconds in the date difference (as they're not included in the %a format). To include those, we simply use the hour, minute and second properties available on the DateInterval object and convert them into seconds as shown in the example above.

Hope you found this post useful. It was published 01 Jan, 2021. Please show your love and support by sharing this post.

In this article, we will see how to calculate the difference between 2 dates in PHP, along with understanding its implementation through the examples. Given two dates ie., start_date and end_date & we need to find the difference between the two dates.

Consider the below example:

Input: start_date: 2016-06-01 22:45:00 
       end_date: 2018-09-21 10:44:01
Output: 2 years, 3 months, 21 days, 11 hours, 59 minutes, 1 seconds
Explanation: The difference of 2 dates will give the date in complete format.

Method 1: Using date_diff() Function

This function is used to find the difference between two dates. This function will return a DateInterval object on the success and returns FALSE on failure.

Example: This example illustrates the use of the date_diff() function to calculate the difference between the 2 dates.

PHP

<?php

  $datetime1 = date_create('2016-06-01');

  $datetime2 = date_create('2018-09-21');

  $interval = date_diff($datetime1, $datetime2);

  echo $interval->format('%R%y years %m months');

?>

Output:

+2 years 3 months

Method 2: To use the date-time mathematical formula to find the difference between two dates. It returns the years, months, days, hours, minutes, seconds between two specified dates.

Example: In this example, we will be using the date-time mathematical formula to calculate the difference between the dates that will be returned in years, months, days, hours, minutes, seconds.

PHP

<?php

  $date1 = strtotime("2016-06-01 22:45:00");

  $date2 = strtotime("2018-09-21 10:44:01");

  $diff = abs($date2 - $date1);

  $years = floor($diff / (365*60*60*24));

  $months = floor(($diff - $years * 365*60*60*24)

                                 / (30*60*60*24));

  $days = floor(($diff - $years * 365*60*60*24 -

               $months*30*60*60*24)/ (60*60*24));

  $hours = floor(($diff - $years * 365*60*60*24

         - $months*30*60*60*24 - $days*60*60*24)

                                     / (60*60));

  $minutes = floor(($diff - $years * 365*60*60*24

           - $months*30*60*60*24 - $days*60*60*24

                            - $hours*60*60)/ 60);

  $seconds = floor(($diff - $years * 365*60*60*24

           - $months*30*60*60*24 - $days*60*60*24

                  - $hours*60*60 - $minutes*60));

  printf("%d years, %d months, %d days, %d hours, "

       . "%d minutes, %d seconds", $years, $months,

               $days, $hours, $minutes, $seconds);

?>

Output:

2 years, 3 months, 21 days, 11 hours, 59 minutes, 1 seconds

Method 3: This method is used to get the total number of days between two specified dates.

PHP

<?php

  $start_date = strtotime("2018-06-08");

  $end_date = strtotime("2018-09-19");

  echo "Difference between two dates: "

      . ($end_date - $start_date)/60/60/24;

?>

Output:

Difference between two dates: 103

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


How will you get the difference between 2 datetime values in seconds in php?

1 Answer. Show activity on this post. $timeFirst = strtotime('2011-05-12 18:20:20'); $timeSecond = strtotime('2011-05-13 18:20:20'); $differenceInSeconds = $timeSecond - $timeFirst; You will then be able to use the seconds to find minutes, hours, days, etc.

How do you calculate seconds between two times?

To get the total seconds between two times, you multiply the time difference by 86400, which is the number of seconds in one day (24 hours * 60 minutes * 60 seconds = 86400). Note.

How can I get minutes between two dates in php?

php $start = strtotime('12:01:00'); $end = strtotime('13:16:00'); $mins = ($end - $start) / 60; echo $mins; ?>

How can I compare two time in php?

php $start = strtotime("12:00"); $end = // Run query to get datetime value from db $elapsed = $end - $start; echo date("H:i", $elapsed); ?>