K20GH
K20GH

Reputation: 6263

Format Unix Timestamp with Timezone?

Lets say I've got my Unix Timestamp of 1373623247. Now I understand that the timestamps are just seconds since X. The issue I have is the formatting of it.

The server I use is hosted in Germany, however I am in the UK so the output is 12-07-13 12:01:01, when actually its only 11:01:01 here.

The code I am using is as below:

$date = 1373623247;
echo date("j-m-y h:i:s",$date);

What I did was use date_create and timezone as follows:

$date1 = date("j-m-y h:i:s",$date);
$dateobj = date_create("$date1", timezone_open('Europe/London'));
echo date_format($dateobj,"j-m-y h:i:s") . "\n";

The issue I now have is that it's actually adjusted the date to tomorrow, and hasn't altered the time!

Upvotes: 0

Views: 156

Answers (1)

Jon
Jon

Reputation: 437336

You do not need to involve date at all:

$date = 1373623247;
$dateobj = date_create_from_format("U", $date);
date_timezone_set($dateobj, timezone_open('Europe/London'));
echo date_format($dateobj,"j-m-y h:i:s") . "\n";

This code converts the timestamp directly to a DateTime instance using the U format specifier. It's both shorter and cleaner to not work with date, as you don't need to worry about the server's default timezone at all.

Pro tip: date and strtotime get much coverage, and in certain cases are very convenient, but DateTime can do everything on its own and IMHO results in code that is much more maintainable.

Upvotes: 2

Related Questions