Monday 21 November 2011

Converting a Long into a Date/Time (MySQL)

In MySQL, sometimes people store timestamps as long values (time since epoch, etc.)

In order to turn that into a date, you need to do the following in MySQL:

SELECT FROM_UNIXTIME(event_time) FROM MY_TABLE


or if you like a date nicely formatted, then:

SELECT DATE_FORMAT(FROM_UNIXTIME(event_time), '%d/%m/%y %h:%i%p') FROM MY_TABLE


NB: This assumes that your event_time is in seconds. If you are using Java, for example, then you will have probably stored your timestamp in millisconds (as kicked out by System,currentTimeMillis() ) so in this instance, MySQL will rather rudely just return NULL.

To fix this, simply divide by 1000 first as follows:


SELECT FROM_UNIXTIME(event_time/1000) FROM MY_TABLE


or if you like a date nicely formatted, then:

SELECT DATE_FORMAT(FROM_UNIXTIME(event_time/1000), '%d/%m/%y %h:%i%p') FROM MY_TABLE

5 comments:

  1. You are missing your underscores in FROM_UNIXTIME ;)

    Link to official doc for those interested:
    http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_from-unixtime

    ReplyDelete
  2. Thanks so much for the /1000 answer. I was getting null and scratching my head for awhile. Did not dawn on me that it was in milliseconds.

    ReplyDelete
  3. Made my day. In my project java milliseconds were stored as long value in mysql. Dividing by 1000 did the trick. Thanks

    ReplyDelete
  4. Very useful indeed! I used that function to convert from a php microtime value stored in a mysql table column.

    ReplyDelete
  5. Returuns NULL for 1577448860548

    ReplyDelete