shtaffa
asked on
MS SQL unix timestamp to mm/dd/yyyy conversion
I have a field in a database that contains unix timestamps. I recently discovered that it would be handy to have actual dates in the database for troubleshooting purposes. I only need mm/dd/yyyy, nothing more detailed. I added a column for the date and have been running a clumsy lookup/update query using php. I'm having php do the conversion from unix to actual date. Unfortunately, it's taking forever.
Is there some way within the contructs of SQL to read the unix timestamp from a column and write the corresponding mm/dd/yyyy date format to another column?
Is there some way within the contructs of SQL to read the unix timestamp from a column and write the corresponding mm/dd/yyyy date format to another column?
And as I test in sql 2005... it looks like there is a quote missing, so:
DATEADD(second, <unixtimestampvalue>, {d '1970-01-01'})
DATEADD(second, <unixtimestampvalue>, {d '1970-01-01'})
ASKER
Being only moderately fluent in the language of SQL, would it be possible to get a complete example of how to do what I'm trying to accomplish?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
The query you supplied worked really quick. However, is there a way to format the converted date? For an example, it added "Oct 1 2011" to the date column. Is it possible to have it formatted as "10/01/2011"?
SQL does NOT format the stored DATETIME object. What you are seeing is the result of your default or session language. You can set your language to English and it will default to MM/DD/YYYY display. A DATETIME is a DATETIME, though. And just to elaborate, a UNIX timestamp represents the number of seconds since the UNIX epoch which happens to be 1970-01-01. There really is no reason to use the ODBC canonical form {d '1970-01-01'}.
DATEADD(ss, {unix timestamp}, '19700101')
Works just fine by the way.
DATEADD(ss, {unix timestamp}, '19700101')
Works just fine by the way.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you gentlemen.
I ended up using the following query:
UPDATE <MyTable>
SET <ConvertedDate = CONVERT(CHAR(10), DATEADD(second, <UnixTimeStamp>, {d '1970-01-01'}), 101)
I ended up using the following query:
UPDATE <MyTable>
SET <ConvertedDate = CONVERT(CHAR(10), DATEADD(second, <UnixTimeStamp>, {d '1970-01-01'}), 101)
Ah, your column is actually character data. For the reasons I said, this is not a best practice, but if consistent the conversion back is trivial. CONVERT(DATETIME, ConvertedDate, 101)
Anyway, best regards and happy coding,
Kevin
Anyway, best regards and happy coding,
Kevin
DATEADD(second, @timestamp, {d '1970-01-01}) where @timestamp is the value for your unix timestamp?