converting Epoch timestamp to sql server(human readable format)

Posted on

converting Epoch timestamp to sql server(human readable format) – This article will take you through the common SQL errors that you might encounter while working with sql, sql-server,  tsql. The wrong arrangement of keywords will certainly cause an error, but wrongly arranged commands may also be an issue. SQL keyword errors occur when one of the words that the SQL query language reserves for its commands and clauses is misspelled. If the user wants to resolve all these reported errors, without finding the original one, what started as a simple typo, becomes a much bigger problem.

SQL Problem :

I have a problem in converting the Unix timestamp to sql server timestamp.

I have a data in excel sheet and I will import that data through a tool. So I am looking for a code or syntax which can convert that Epoch timestamp to sql server timestamp.

I have 3 different columns with the same format. How can I change the values in those columns.

For Example:

  • Epoch timestamp —1291388960
  • sql server timestamp— 2010-12-03 15:09:20.000

Solution :

I have 3 different columns with the same format. How can I change the values in those columns.

To update 3 columns in a table, you can pair DATEADD seconds to the epoch (1 Jan 1970) with the column name, i.e.

update tbl set
    datetimecol1 = dateadd(s, epochcol1, '19700101'),
    datetimecol2 = dateadd(s, epochcol2, '19700101'),
    datetimecol3 = dateadd(s, epochcol3, '19700101')

You can’t update in place since a bigint column cannot also be a datetime column. You have to update them into 3 other columns.

Use the DATEADD function:

SELECT DATEADD(ss, 1291388960, '19700101')

…specifying a date of January 1st, 1970. In this example, it was provided in the YYYYMMDD format.

DATEADD will return a DATETIME data type, so if you have a table & column established — you can use the function to INSERT/UPDATE depending on your needs. Provide details, and I’ll clarify. Once you have a DATETIME to work with, you can use CAST or CONVERT to format the date in TSQL.

Finding SQL syntax errors can be complicated, but there are some tips on how to make it a bit easier. Using the aforementioned Error List helps in a great way. It allows the user to check for errors while still writing the project, and avoid later searching through thousands lines of code.

Leave a Reply

Your email address will not be published. Required fields are marked *