Subtract time in PHP
Asked Answered
C

3

9

I have been looking for an answer for a few hours now, but I can't find one.

I'm writing a simple script. The user sets their work start and end time. So, for example, somebody is working from 8:00 to 16:00. How can I subtract this time to see how long the person has been working?

I was experimenting with strtotime(); but without success...

Centric answered 28/3, 2011 at 18:42 Comment(0)
C
32

A bit nicer is the following:


$a = new DateTime('08:00');
$b = new DateTime('16:00');
$interval = $a->diff($b);

echo $interval->format("%H");

That will give you the difference in hours.

Cysto answered 28/3, 2011 at 18:51 Comment(1)
I wonder if it can convert the entire interval into seconds? ->format('%S') just gave me the seconds part of the interval output, not the total calculated seconds elapsed.Stockholder
P
10

If you get valid date strings, you can use this:

$workingHours = (strtotime($end) - strtotime($start)) / 3600;

This will give you the hours a person has been working.

Phaedrus answered 28/3, 2011 at 18:47 Comment(2)
You can divide by 60 instead of 3600 to get minutes and divide by 60 and round down (floor()) to get full hours and get the remainder of minutes%60 to get the minutes.Phaedrus
date ( 'H:i' , $workingHours ). I would not recommend strtottime here as strtotime gives you back the unix timestamp of a date.Bourgeoisie
P
3

Another solution would be to go through the Unix-timestamp integer value difference (in seconds).

<?php
    $start = strtotime('10-09-2019 12:01:00');
      $end = strtotime('12-09-2019 13:16:00');

      $hours = intval(($end - $start)/3600);
      echo $hours.' hours'; //in hours

      //If you want it in minutes, you can divide the difference by 60 instead
      $mins = (int)(($end - $start) / 60);
      echo $mins.' minutues'.'<br>';
?>

This solution would be a better one if your original dates are stored in Unix-timestamp format.

Pleasurable answered 23/9, 2019 at 14:23 Comment(1)
Welcome to Stack Overflow. When answering an eight year old question with existing answers it is useful to point out what new aspect of the question your answer addresses. Code only answers can almost always be improved by adding explanation including why and how the code solves the problem.Amaya

© 2022 - 2025 — McMap. All rights reserved.