Jump to content
  • Advertisement
Sign in to follow this  
future_man

Subtract timestamp time from current time

This topic is 2146 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to subtract database timestamp from current server time. The formatted time that is returned to me from my database is "2013-09-01 22:05:39" and I use function date("Y-m-d H:i:s"); so that my server time I get in php is in the same format.

 

How can I get a result in hours? Example: 2013-09-01 22:05:39  minus 2013-09-02 22:05:39 equals 24 hours ???

Share this post


Link to post
Share on other sites
Advertisement
The php DateTime object has a diff function that subtracts the two, and takes into account things like daylight saving time and other fun quirks of time.




One funny thing about time, the math doesn't always work out that two consecutive days are 24 hours apart.

Daylight Saving Time means sometimes subtracting a day means 25 hours, sometimes 23 hours. The leap-day held every 4 years is predictable, but leap-seconds that keep clocks coordinated are not predictable. If you use sub-second increments there are small adjustments that happen frequently.

Share this post


Link to post
Share on other sites

OK I solved my problem like this:

$current_time = date_create(date("Y-m-d H:i:s"));
$last_time = date_create(date("Y-m-d H:i:s", strtotime(get_last_update_time($user_name))));
$result = date_diff($current_time, $last_time);

echo $result->format('%Y-%m-%d %H:%i:%s');

but it echoes my result like so: "00-0-0 03:40:56", with all the days etc.. How do I format this so that it only show hours, lets say like so: "232156". With all the days, months years, formatted to hours?

Share this post


Link to post
Share on other sites
The php manual is awesome for this. date_diff returns either a DateInterval object or a boolean.

To calculate just hours I would use this formula: hours = (days * 24) + (h) + (i / 60) + (s / 3600)

Some notes:
1. Test for failure before using the DateInterval or you might throw exceptions.
2. DateInterval-> days is an integer rounded down.
3. Don't do the division in a loop. Precalc to a constant and multiply.


EDIT: Also if you are looking for straight linear time diffs then I would avoid timestamps in date formats all together since you can run into funky 'leap' issues. Store your timestamps in milliseconds since epoch and divide from there.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!