Domanda

I run the following MySQL query:

select unix_timestamp('2011-03-13 02:00:13'), unix_timestamp('2011-03-13 02:20:41'), unix_timestamp('2011-03-13 02:40:10');

And get the following odd result:

1300003200, 1300003200, 1300003200

I think there's some kind of daylight savings time going on here, though it still seems odd that all the values are magically the same.

I'd appreciate suggestions of how to prevent MySQL from doing daylight savings time things here, as well as some explanation as to why all the results are the same.

È stato utile?

Soluzione

MySQL's behavior is correct, if your server's time zone "CDT" observes DST and you haven't set your session time zone to something different.

The UNIX_TIMESTAMP() function uses your session's time zone to interepret the value you give it.

The server interprets date as a value in the current time zone and converts it to an internal value in UTC.

...

Note: If you use UNIX_TIMESTAMP() and FROM_UNIXTIME() to convert between TIMESTAMP values and Unix timestamp values, the conversion is lossy because the mapping is not one-to-one in both directions. For example, due to conventions for local time zone changes, it is possible for two UNIX_TIMESTAMP() to map two TIMESTAMP values to the same Unix timestamp value. FROM_UNIXTIME() will map that value back to only one of the original TIMESTAMP values.

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

The timestamps in question did not exist in your time zone, so the server is giving you the most accurate possible answer... it's the time in UTC that the clock moved forward to, when the time moved forward, less than an hour prior to your datetime literals, which represent "times that never existed on that day" in your time zone.

If those timestamps are intended to be times in your local time zone, then the answer is that those are invalid values, since that time never happened where you are. On the other hand, if those timestamps are actually assumed to already be in UTC, then you're not getting the correct answer from UNIX_TIMESTAMP() on any query, because the time is being converted "from" a time zone it isn't actually expressed in.

If you SET @@TIME_ZONE = 'UTC'; and repeat the queries, you'll see what I mean, since UTC has no DST. This statment only sets your session's time zone, not the whole server.

If running SET @@TIME_ZONE = 'UTC'; gives you an error message such as ERROR 1298 (HY000): Unknown or incorrect time zone: 'UTC', it is likely that you have not populated MySQL with timezone information. As described here you can load this information by using the command:

mysql_tzinfo_to_sql /usr/share/zoneinfo/ | mysql -u root mysql -p

where the path /usr/share/zoneinfo may need to be replaced with a path specific to your system.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top