Francesco
Francesco

Reputation: 25239

PHP Adding and Subtracting Time to a given timestamp

I get a timestamp from mysql like

2012-04-12 16:42:33

in PHP how can i subtract hours, or basically how can i change timezone (-3 hours)?

Upvotes: 1

Views: 3140

Answers (3)

Dfranc3373
Dfranc3373

Reputation: 2177

$hours = 3;

$time_old = "2012-04-12 16:42:33";

$time_new = strtotime($time_old);

$time_new = $time_new - (60 * $hours);

date($time_new);

This will allow you to dynamically change the hours by changing $hours.

Upvotes: 0

mistalee
mistalee

Reputation: 851

You should use PHP's DateTime. You can check out the supported formats and then create a new object:

$date=new DateTime("2012-04-12 16:42:33");

This object also supports changing timezones and other conversions. Setting a new timezone (from PHP manual):

$date->setTimezone(new DateTimeZone('Pacific/Chatham'));

Upvotes: 0

Brad
Brad

Reputation: 163232

strtotime('-3 hours', strtotime('2012-04-12 16:42:33'));

http://php.net/manual/en/function.strtotime.php

Changing timezones is technically a bit more tricky, since the way your timestamp is formatted, we don't know what timezone the original is in. So, this code should suffice.

Upvotes: 1

Related Questions