1

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?

2
  • Convert both time in time stamp by using strtotime. Commented Mar 28, 2013 at 8:32
  • Difference must be less than 24h? Should consider changing the summer and winter time? Commented Mar 28, 2013 at 8:32

4 Answers 4

2

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'; 
Sign up to request clarification or add additional context in comments.

Comments

2
<?php $d1 = strtotime('1:30 PM'); $d2 = strtotime('8:20 AM'); $diff = abs($d1-$d2); echo "Difference is $diff secs"; ?> 

9 Comments

Its not showing the correct different if I am converting seconds into the hours using gmdate("h:i:s",abs($d1 - $d2))
@jks I am getting it as 5hours and 10 min ... which I think is correct.. ?
it showing diff between 5:00 PM and 9:29 AM is 7.5166666666667
I am considering am/pm also here for getting difference
its correct ,, I think difference is 7 hours and 30 min .. mean 7.5 hours .. whats the problem .... ?
|
1

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)

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.