Php datediff in hours

date_diff

Returns the difference between two DateTimeInterface objects.

Parameters

Should the interval be forced to be positive?

Return Values

The DateInterval object represents the difference between the two dates.

The return value more specifically represents the clock-time interval to apply to the original object ( $this or $originObject ) to arrive at the $targetObject . This process is not always reversible.

The method is aware of DST changeovers, and hence can return an interval of 24 hours and 30 minutes , as per one of the examples. If you want to calculate with absolute time, you need to convert both the $this / $baseObject , and $targetObject to UTC first.

Examples

Example #1 DateTimeImmutable::diff() example

$origin = new DateTimeImmutable ( ‘2009-10-11’ );
$target = new DateTimeImmutable ( ‘2009-10-13’ );
$interval = $origin -> diff ( $target );
echo $interval -> format ( ‘%R%a days’ );
?>

$origin = date_create ( ‘2009-10-11’ );
$target = date_create ( ‘2009-10-13’ );
$interval = date_diff ( $origin , $target );
echo $interval -> format ( ‘%R%a days’ );
?>

Читайте также:  Setinterval или settimeout javascript

The above examples will output:

Example #2 DateTimeInterface::diff() during DST changeover

$originalTime = new DateTimeImmutable ( «2021-10-30 09:00:00 Europe/London» );
$targedTime = new DateTimeImmutable ( «2021-10-31 08:30:00 Europe/London» );
$interval = $originalTime -> diff ( $targedTime );
echo $interval -> format ( «%H:%I:%S (Full days: %a)» ), «\n» ;
?>

The above example will output:

Example #3 DateTime object comparison

$date1 = new DateTime ( «now» );
$date2 = new DateTime ( «tomorrow» );

var_dump ( $date1 == $date2 );
var_dump ( $date1 < $date2 );
var_dump ( $date1 > $date2 );
?>

The above example will output:

bool(false) bool(true) bool(false)

See Also

  • DateInterval::format() — Formats the interval
  • DateTime::add() — Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
  • DateTime::sub() — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

User Contributed Notes

Источник

PHP Calculate Difference Between Two Dates in Hours, Minutes and Seconds

There are many date functions and methods in PHP that you can use to get the time difference between two or more dates. Sometimes, you need to calculate or find the time difference between two dates PHP.

If you know the functions and methods to calculate the time difference in PHP. Then it is very simple for you to calculate the time difference between two dates. But, In this tutorial, you have learned simple and easy ways how to calculate/find the time difference between two dates in hours and minutes, and seconds with PHP.

PHP Calculate the Difference Between Two Dates in Hours, Minutes, and Seconds

Using the following methods and examples, you can calculate/find the time difference between two dates in hours and minutes, and seconds with PHP:

  • Method 1: Using the DateTime object with Diff()
  • Method 2: Using the strtotime() function with gmdate()
  • Method 3: Using the strtotime() function with date_diff()

Method 1: Using the DateTime object with Diff()

To calculate/get time difference between two dates using dateTime object and diff() function.

Here is an example to calculate the time difference in hours, minutes and seconds between two dates using dateTime object and diff() function:

$date1 = new DateTime('2022-01-01 00:00:00'); $date2 = new DateTime('2022-01-02 12:30:15'); $interval = $date1->diff($date2); echo $interval->format('%H hours, %i minutes, %s seconds');

Method 2: Using the strtotime() function with gmdate()

Using the strtotime and gmdate() function, you calculate the time difference in hours, minutes and seconds between two dates.

Here is an example to calculate the time difference in hours, minutes, and seconds between two dates using the strtotime and gmdate() function:

$date1 = strtotime('2022-01-01 00:00:00'); $date2 = strtotime('2022-01-02 12:30:15'); $diff = $date2 - $date1; echo gmdate('H hours, i minutes, s seconds', $diff);

Method 3: Using the strtotime() function with date_diff()

To calculate time difference between two dates in hours, minutes and seconds using date_diff() and strtotime() in PHP.

Here is an example to calculate the time difference in hours, minutes, and seconds between two dates using the strtotime and date_diff() function:

$date1 = strtotime('2022-04-27 10:00:00'); $date2 = strtotime('2022-04-27 11:30:00'); $diff = abs($date2 - $date1); $interval = date_diff(date_create("@$date1"), date_create("@$date2")); $hours = $interval->format('%h'); $minutes = $interval->format('%i'); $seconds = $interval->format('%s'); echo "The time difference is: $hours hours, $minutes minutes, and $seconds seconds.";

Conclusion

Calculating the time difference between two dates in PHP is a simple process that involves getting the dates, calculating the time difference, and getting the hours, minutes, and seconds. With the built-in functions in PHP, you can easily perform this task and display the result to the user.

Источник

Php php datetimer datediff in hours code example

Below would correct the most popular answer to return hours as an integer and minutes as a decimal (ie 6.5 hours). Using HOUR will only return hours as an integer.

Time difference in hours and min in php HH:MM format for d/m/Y

This format is incorrect and unrecognized by strtotime (see the third note) I suspect that your timezone is GMT-8 and you will always get 16h from dates in this format.

You have to convert manually this date to format recognized by php in order to do some calculations

$from = $_SESSION['loginT']; $to = date('m/d/Y h:i A'); $diff_seconds = strtotime($to) - strtotime($from); $stat = floor($diff_seconds/3600).'H:'.floor(($diff_seconds%3600)/60).'M'; 
$_SESSION['loginT'] = date('m/d/Y h:i A'); 
21/10/2012 - 06:37pm 21/11/2012 - 06:07pm 23H:30M 

Datetime diff php in hours Code Example, date_default_timezone_set(«Africa/Johannesburg»); $now = new DateTime(); $future_date = new DateTime(‘2020-10-21 00:00:00’); $interval = …

Php — One Hour Earlier Than Given Datetime

strtotime will give you the unix timestamp of your date. From this timestamp, you then subtract your hour:

$date = strtotime($date) - 3600; // 3600 = 60 * 60 

If you call strtotime($date — 3600) , it’s like obtaining the time for -3600 (e.g. strtotime(-3600) ) which makes no sense because strtotime expects a string as first argument.

 $testDateStr = strtotime($date); $finalDate = date("Y-m-d H:i:s", strtotime("-1 hour", $testDateStr)); 

86400 seconds is one DAY, not one hour.

The output of strtotime() is a unix timestamp. 3600 seconds earlier is that timestamp minus one hour. So:

$date = strtotime($somestring); $hourago = $date - 3600; 

Or, depending on the original format of $somestring:

$hourago = strtotime($somestring . " - 1 hour"); 

And don’t forget about date_default_timezone_set()

Date — How to calculate time difference in PHP?, Use the diff () method of PHP’s DateTime class like this:- $lastWeek = new DateTime (‘last thursday’); $now = new DateTime (); var_dump ($now->diff ($lastWeek, true)); This will give you a DateInterval object:-

TIMEDIFF() function in PHP?

If you use php 5.3 or after you can use the following code

$to_time = new DateTime(array_search( 'time2.Time', $aCols )); $from_time = new DateTime(array_search( 'time1.Time', $aCols )); $interval = $date1->diff($date2); $value = $interval->format('%H:%i:%s'); 

or before 5.3 try something like this:

$date1 = strtotime("2012-09-13 12:14:24.453"); $date2 = strtotime("2012-09-15 14:21:28.453"); $interval = $date2 - $date1; $seconds = $interval % 60; $minutes = floor(($interval % 3600) / 60); $hours = floor($interval / 3600); echo $hours.":".$minutes.":".$seconds; 

Use strtotime() if needed to convert the values to timestamps (which they should already be ideally) and then just subtact the two.

$dattTime = new DateTime(); $dateTime2 = new DateTime("2012-09-11 10:25:00"); $interval = $dattTime->diff($dateTime2); var_dump($interval->format('%H:%i:%s')); $hours = $interval->h + ($interval->d*24); var_dump("Total Hours: " . $hours . " hrs"); 
string '08:17:15' (length=8) string 'Total Hours: 608 hrs' (length=20) 

Php datediff in hours Code Example, follow. grepper; search snippets; pricing; faq; usage docs ; install grepper; log in

Mysql timediff to hours

TIMEDIFF(endDate, startDate) outputs in DateTime format, so flat that to timestamp and devide by (60*60)

SELECT (UNIX_TIMESTAMP(TIMEDIFF(endDate, startDate))/(60*60)) AS hours_difference FROM tasks 

Edit: Alternatively,TimestampDiff may also provide a valid solution in more elegant way providing its example:

SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01'); 
SELECT TIMESTAMPDIFF(HOUR, startDate, endDate) AS hours_different FROM tasks 

NOTE the most voted up answer in this chain is INCORRECT! Using HOUR will only return hours as an integer. Below would correct the most popular answer to return hours as an integer and minutes as a decimal (ie 6.5 hours).

TIME_TO_SEC(TIMEDIFF(endDate, startDate))/3600 as hours 
HOUR(TIMEDIFF(endDate, startDate)) 

might work—if I’m reading the docs correctly.

Php — mysql timediff to hours, HOUR(TIMEDIFF(«2050-01-01 00:00:00», «2012-01-01 00:00:00»)) Result: 838. fails. As we see in the example above, it surprisingly even works beyond the timestamp limitation in year 2038. The maximum hours which are returned by HOUR(TIMEDIFF(dateEnd, dateStart)) is 838, because TIMEDIFF is …

Источник

date_diff

Возвращает разницу между двумя DateTimeInterface объектами.

Список параметров

Дата и время для сравнения.

Используется, чтобы вернуть абсолютную разницу.

Возвращаемые значения

DateInterval объект представляет разницу между двумя датами или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования DateTime::diff()

$datetime1 = new DateTime ( ‘2009-10-11’ );
$datetime2 = new DateTime ( ‘2009-10-13’ );
$interval = $datetime1 -> diff ( $datetime2 );
echo $interval -> format ( ‘%R%a дней’ );
?>

$datetime1 = date_create ( ‘2009-10-11’ );
$datetime2 = date_create ( ‘2009-10-13’ );
$interval = date_diff ( $datetime1 , $datetime2 );
echo $interval -> format ( ‘%R%a дней’ );
?>

Результат выполнения данных примеров:

Пример #2 Сравнение объектов DateTime

Замечание:

В PHP 5.2.2 объекты DateTime сравнивались при помощи операторов сравнения.

$date1 = new DateTime ( «now» );
$date2 = new DateTime ( «tomorrow» );

var_dump ( $date1 == $date2 );
var_dump ( $date1 < $date2 );
var_dump ( $date1 > $date2 );
?>

Результат выполнения данного примера:

bool(false) bool(true) bool(false)

Смотрите также

  • DateInterval::format() — Форматирует интервал
  • DateTime::add() — Добавляет заданное количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime
  • DateTime::sub() — Вычитает заданное количество дней, месяцев, лет, часов, минут и секунд из времени объекта DateTime

Источник

Оцените статью