0

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!

2
  • Use date_default_timezone_set to set your timezone. Commented Jul 12, 2013 at 10:12
  • You are not getting tomorrow. 12-07-13 is parsed as 2012-07-13. Commented Jul 12, 2013 at 10:22

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this worked great. Now just the issue around Greenwich Mean Time and British Summer Time...
@K20GH: I just realized that and edited to reflect. The correct thing to do is parse the timestamp and then assert that you want it to be considered as London local time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.