Search code examples
mysqlunix-timestamp

How to convert this date into a unix timestamp in mysql alone?


This is the date: 2018-01-25T13:39:40-05:00
Its from an API.

So far, I did this: SELECT UNIX_TIMESTAMP(STR_TO_DATE('2018-01-25T13:39:40-05:00', '%M %d %Y %h:%i%p')) AS time

But its giving me NULL.
I think -05:00 is timezone. But T is, I don't know.

Maybe perhaps there is another way take out T and -05:00 and convert 24hrs to 12hrs


Solution

  • You don't have to use the STR_TO_DATE function.

    You can directly use UNIX_TIMESTAMP.

    UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC.

    The date argument may be a DATE, DATETIME, or TIMESTAMP string, or a number in YYMMDD, YYMMDDHHMMSS, YYYYMMDD, or YYYYMMDDHHMMSS format.

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

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

    SELECT UNIX_TIMESTAMP('2018-01-25T13:39:40-05:00') AS time
    

    http://sqlfiddle.com/#!9/b2206f/1