简体   繁体   中英

MySQL convert DateTime (storing a UTC_TIMESTAMP) to number of seconds 1970

There are many similar questions out there but I believe this one is unique. (Sorry if it isn't)

Our database has datetime field named "date_sampled", of which we store with UTC_TIMESTAMP()

Our goal is to return the number of seconds since 1970. I noticed UNIX_TIMESTAMP() if supplied no argument returns the current UNIX_TIMESTAMP() and if a datetime (ie 2011-10-10) is passed, it returns a timestamp in seconds.

However UTC_TIMESTAMP() does not work like this, it returns a current UTC Timestamp. 返回当前UTC时间戳。

So how can I convert my DateTime field (holding a UTC datetime) into the seconds from 1970 in MySQL? If it can't be done in MySQL, then a PHP solution will work.

Thanks.

There is a TIMESTAMPDIFF function in MySQL, you can use it something like

SELECT TIMESTAMPDIFF(SECOND,'1970-01-01 00:00:00', YourUTCDateFromSomewhere)

More details in the docs - http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timestampdiff

Interesting problem... I have no clue how to do this with SQL... but the PHP solution would be to use the strtotime() function..

<?php
echo strtotime('2011-10-10');
?>

The above example returns the value 1318219200 which is the number of seconds that have passed since the 1970 epoch

What were you trying to get UTC_TIMESTAMP to do that UNIX_TIMESTAMP doesn't? Unix timestamps are in UTC by definition.

I'm assuming the problem you're having is that, even though you're storing your datetimes in UTC, UNIX_TIMESTAMP is giving you a timezone-offset result, so you're getting a value several hours off from what you're expecting.

UNIX_TIMESTAMP respects MySQL's time_zone variable , so if all your dates are in UTC, you can just set your session's time_zone variable to UTC, which will cause UNIX_TIMESTAMP to do no timezone conversion when converting a datetime to a timestamp.

SET time_zone = '+00:00'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM