Kenny Cason
Kenny Cason

Reputation: 12328

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 (i.e. 2011-10-10) is passed, it returns a timestamp in seconds.

However UTC_TIMESTAMP() does not work like this, it Only returns a current UTC Timestamp.

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.

Upvotes: 1

Views: 1852

Answers (3)

John Flatness
John Flatness

Reputation: 33829

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'

Upvotes: 1

Andrew
Andrew

Reputation: 27344

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

Upvotes: 2

Tyrick
Tyrick

Reputation: 2966

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

Upvotes: 1

Related Questions