1

I have a date_diff() time like 00:30:30. I want to convert to only hour like as 0.30Hour. I have used bellow code,

<code>
   $start=date_create($tempStart_emp);
   $end=date_create($current_date);
   $diff=date_diff($start,$end);
   echo $diff->format("%H:%I:%S");//00:30:30
</code>

my expected outpur://0.30Hour Is it possible??

Salman Quader
  • 195
  • 2
  • 13

1 Answers1

3

I assume, your wanted output is 0.5 - half an hour. If you want 0.30 you just can replace the : in your format string with a dot ..

You can get the interval in seconds by subtracting the time-stamps of start and end time:

$diff_s = $end->getTimestamp() - $start->getTimestamp();

And then just divide by 3600 to get the decimal hours:

$diff_h = $diff_s/3600;
echo round($diff_h, 2);

See working example on ideone.com.

Summarizing a discussion in the comments:

Of course time zone and daylight saving shifts are always an issue, when you work with Dates and Times. If (!) you consider the right time zones in construction of your DateTime objects, the timestamp diff in this answer will show you the seconds really(*) passed in between. And this may differ from the time seemingly has passed on your wall clock.

(*) The time really passed? No, unfortunately not. When it comes to leap seconds, the difference of two Unix timestamps is not necessarily the number of seconds passed. At least, this error by its nature is relatively small. See here for more info on that: Unix time and leap seconds

Community
  • 1
  • 1
DerVO
  • 3,679
  • 1
  • 23
  • 27
  • Small typo - of course we have to divide `$diff_s` by 3600, which is just an int - getTimestamp returns the unix timestamp of a given DateTime object as an int. I added a link to an example. – DerVO May 17 '16 at 09:30
  • Please note that this will fail if the interval spans a daylight savings shift – Mark Baker May 17 '16 at 09:48
  • @MarkBaker I don't agree. I thought about this issue when posting and I had stuck with this pure timestamp solution. Of course this depends on your exact definition of the desired output, but especially when it comes to DST shifts and leap seconds, the timestamp is in my eyes the most intuitive way of measuring relatively small time intervals (like in the given example). – DerVO May 20 '16 at 08:38
  • The timestamp works perfectly well, as long as people are aware of the timezone/dst when it ccomes to interpreting results - but we see so many questions here that indicate a complete lack of understanding that the timestamp is a UTC value, and of the various functions for creating/displaying a timestamp value in different timezones – Mark Baker May 20 '16 at 08:42
  • 1
    @MarkBaker I have added an additial note to the answer regarding this issue. Feel free to add/correct some information as well. – DerVO May 20 '16 at 12:01
  • @DerVO - nothing really to add (without getting bogged down in real minutiae), you've summed it up pretty well – Mark Baker May 20 '16 at 12:03