J.K.A.
J.K.A.

Reputation: 7404

How to I substract time in PHP along with AM/PM

I have time format say:

$start_time; (example: 1:30 PM)
$system_time; (example: 8:20 AM)        
echo $time_left_for_discussion = $start_time - $system_time;

I want to substract $start_time - $system_time. But its not showing the correct result.

How can I deal with this kind of time substraction?

Upvotes: 1

Views: 1075

Answers (4)

alwaysLearn
alwaysLearn

Reputation: 6950

<?php
  $d1 = strtotime('1:30 PM');
  $d2 = strtotime('8:20 AM');
   $diff = abs($d1-$d2);

  echo "Difference is $diff secs";

?>

Upvotes: 2

Rijk
Rijk

Reputation: 11301

Use DateTime::createFromFormat() on both times, and substract those.

$TimeStart = DateTime::createFromFormat( 'g:i A', $start_time );
$TimeEnd = DateTime::createFromFormat( 'g:i A', $end_time );

$Interval = $TimeStart->diff( $TimeEnd );
$time_left = $Interval->h . 'h' . $Interval->m 'm';

Upvotes: 2

LukeStoneHm
LukeStoneHm

Reputation: 122

Can I recommend you take a look at this http://php.net/manual/en/function.strtotime.php

This is String to time, it is very useful.

Have a good day :D

Upvotes: 1

Gung Foo
Gung Foo

Reputation: 13558

you will want to look at the date() and strtotime() functions.

the way to deal with such a case is to convert the dates into unix timestamps, subtract one timestamp form another and then recreate a date string from the resulting timestamp.

Note: the time() function will return the current system time(-stamp)

Upvotes: 1

Related Questions