172

How do I convert the following format to unix timestamp?

Apr 15 2012 12:00AM

The format I get from DB seems to have AM at the end. I've tried using the following but it did not work:

CONVERT(DATETIME, Sales.SalesDate, 103) AS DTSALESDATE,  
CONVERT(TIMESTAMP, Sales.SalesDate, 103) AS TSSALESDATE

where Sales.SalesDate value is Apr 15 2012 12:00AM
3
  • 1
    Is the date stored as text in the DB ? Commented Jun 21, 2012 at 7:57
  • 1
    Is it really a MySQL question? Your syntax doesn't suggest so. Commented Jun 21, 2012 at 8:08
  • 1
    Seems what the question is about MSSQL. Commented May 23, 2013 at 15:54

4 Answers 4

271

Here's an example of how to convert DATETIME to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))

Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')

Documentation: UNIX_TIMESTAMP, FROM_UNIXTIME

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks .This works.This can also be used in other statements such as update,delete,insert etc
After so many trials your solution worked for me: select * from (SELECT order_increment_id, FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE(order_date, '%d %M %Y %h:%i:%s %p')),'%Y-%m-%d') as order_date, email_sent FROM `packingslip_header` where email_sent=0) t where order_date >= '2019-11-13' ORDER BY order_increment_id ASC This is the date I had 31 Oct 2017 4:16:49 pm so I needed to use %d %M %Y %h:%i:%s %p for STR_TO_DATE
38

You will certainly have to use both STR_TO_DATE to convert your date to a MySQL standard date format, and UNIX_TIMESTAMP to get the timestamp from it.

Given the format of your date, something like

UNIX_TIMESTAMP(STR_TO_DATE(Sales.SalesDate, '%M %e %Y %h:%i%p'))

Will gives you a valid timestamp. Look the STR_TO_DATE documentation to have more information on the format string.

Comments

0

If you want to create a timestamp as returned by java's Date.getTime() you should multiply by 1000.

SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))*1000

Now for a more standard date format use:

SELECT UNIX_TIMESTAMP(STR_TO_DATE('2022-12-14 20:58:00', '%Y-%m-%d %H:%i:%s'))*1000

Comments

-5

From http://www.epochconverter.com/

SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())

My bad, SELECT unix_timestamp(time) Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD. More on using timestamps with MySQL:

http://www.epochconverter.com/programming/mysql-from-unixtime.php

1 Comment

This answer is for MSSQL (although this question has some confusion).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.