user1672353
user1672353

Reputation: 11

Subtract time from strtrotime

I am trying to figure out how to subtract 1 hour form the time being outputted. Our web server is 1 hour ahead of our time. I am using the following to return the time a table was created in our MySQL database.

ini_set('date.timezone', 'America/Los_Angeles');
$con = mysql_connect('localhost','database','password');  
$db = mysql_select_db('database'); 
$sql = mysql_query("SHOW TABLE STATUS WHERE `name`=\"initm\"");  
$foo = mysql_fetch_array($sql);  
$ts = strtotime($foo['Create_time']);
echo "<h3>Last Updated ";
echo date('m/d/Y g:i a T', $ts);
echo "</h3>";  

If I try to subtract time $ts = strtotime($foo['Create_time']-3600);

it returns Last Updated 12/31/1969 4:00 pm PST. I understand it is subtracting from the UNIX timestamp, which is defined as the number of seconds since January 1, 1970 and not from the time in the table.

I tried adding ini_set('date.timezone', 'America/Los_Angeles'); but it just changes the time zone outputted.

Any advice is greatly appreciated. A novice in PHP and MySQL.

Upvotes: 1

Views: 217

Answers (3)

Alain
Alain

Reputation: 36984

Why not :

$query = "SET time_zone = '-6:00'";

This will set your configuration in the same way as SET charset utf8.

Upvotes: 1

Krycke
Krycke

Reputation: 3186

strtotime assumes it's parameter is a string, and converts it to seconds. You need to do the subtraction after the conversion:

$ts = strtotime($foo['Create_time'])-3600;

Upvotes: 2

Marc B
Marc B

Reputation: 360782

SELECT UNIX_TIMESTAMP(Create_time) - 3600 ...

is far easier than multiple round-trips through PHP's and MySQL's date/time processing systems.

However, since strtotime is giving you invalid results, I'm guessing that whatever you're storing in Create_time is not actually a native mysql data/time value, but probably some wonky non-standard date value as a string. That means strtotime() is returning a boolean FALSE to indicate failure, and then you force PHP to convert that false to an integer 0 to handle your "minus 3600" calculation.

You should generally always store things in native formats/types, to prevent occurences such as this. Native allows you to use native facilities for processing. Custom formats mean pain/suffering

Upvotes: 1

Related Questions