1

When I try to turn a german date (date of birth, to be more specific) format into a unix timestamp, I am getting -3600 instead of a 0.

Maybe some summertime thing?

$value = '01.01.1970';
$date = DateTime::createFromFormat ('d.m.Y', $value);
$date->setTime(0, 0);
$value = $date->getTimestamp();

echo $value; // -3600

I always thought there's a 0. What is the best practice when dealing with a situation like this? Timezone is GMT+1, in case it matters. I even tried 01.01.1850, turning it to timestamp and then back to a formated date. Works nicely at home, but at work it showed 31st December 1849.

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

1

I suspect, if you check with date_default_timezone_get, that your server's timezone is not set to UTC. I was able to duplicate this behavior like so:

date_default_timezone_set('Europe/Berlin');
$value = '01.01.1970';
$date = DateTime::createFromFormat ('d.m.Y', $value);
$date->setTime(0, 0);
$value = $date->getTimestamp();

Due to the timezone differences, 1970-01-01 00:00:00 in the Berlin timezone does, in fact, correspond to a negative Unix timestamp of -3600. The Unix timestamp 0 just corresponds to 1970-01-01 00:00:00 in UTC - a negative value simply indicates a time prior to that instant.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
1

That is a great question. One which even threw me off, because of this.

However, in your case Germany was as you said on UTC+01:00, hence on your system the value of $date is 1970-01-01T00:00:00+01:00.

If you reverse the scenario and try to find out what is the date corresponding to timestamp 0, it should help you understand how time zones work with timestamps.

$date = DateTime::createFromFormat ('U', '0');
$date->setTimezone(new DateTimeZone('Europe/Berlin'));
echo $date->format(DATE_ATOM); // 1970-01-01T01:00:00+01:00

Because timestamps are the relative time difference from the UNIX epoch in seconds it will be a different time in different time zone. This count starts at midnight on January 1st, 1970 at UTC. While both Britain and Germany were on UTC+01:00 in 1970, the UNIX epoch started for them on 1970-01-01 01:00:00

In terms of how to best deal with this, well... that is opinion-based. Probably most people would tell you to deal with time in UTC so you don't run into weird issues such as this, and only convert to the right timezone on display, but even the great Jon Skeet had different opinion.

Dharman
  • 30,962
  • 25
  • 85
  • 135