Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract 6 Hours From timestamp Using PHP

Tags:

php

mysql

I have this code to display a date and time from the database. How would I modify it to subtract 6 hours from the timestamp.

date('m-d g:Ga', strtotime($row['time_stamp']))
like image 705
Jeff Thomas Avatar asked Jun 18 '11 03:06

Jeff Thomas


2 Answers

UNIX time stamps are seconds since the Epoch. Simply subtract the number of seconds in six hours:

date('m-d g:Ga', strtotime($row['time_stamp'])-21600)

You could alternatively use strtotime again:

date('m-d g:Ga', strtotime('-6 hours', strtotime($row['time_stamp'])))
like image 171
icktoofay Avatar answered Nov 03 '22 17:11

icktoofay


Since it's in MySQL, you can have MySQL do the calculation for you:

SELECT DATE_FORMAT('...', DATE_SUB(time_stamp, INTERVAL 6 HOUR)) ...

This would save you the overhead of MySQL having to conver its internal representation into a full string, and the overhead of PHP's strtotime() parseing that string just to turn it back into yet another string. While strtotime is magical sometimes, it's definitely not efficient.

like image 29
Marc B Avatar answered Nov 03 '22 18:11

Marc B