Convert Datetime to Unix timestamp - sql

In Microsoft SQL Server 2012 or above, is it possible to convert a datetime value to Unix time stamp in a single select statement? If so, how can it be done?

As Peter Halasz mentions in T-SQL DateTime to Unix Timestamp:
Converting a datetime to unix timestamp is easy, but involves error
prone typing the following:
#timestamp=DATEDIFF(second,{d '1970-01-01'},#datetime)
Where #datetime is the datetime value you want to convert. The {d
‘yyyy-mm-dd’} notation is an ODBC escape sequence.
The function:
CREATE FUNCTION UNIX_TIMESTAMP (
#ctimestamp datetime
)
RETURNS integer
AS
BEGIN
/* Function body */
declare #return integer
SELECT #return = DATEDIFF(SECOND,{d '1970-01-01'}, #ctimestamp)
return #return
END
Try it out now like below #O A:
SELECT UNIX_TIMESTAMP(GETDATE());

maybe this answer will help someone... If you have a problem when you try to convert datetime using datediff function to number of seconds (mssql message: The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.) then use:
select cast(datediff(d,'1970-01-01',#d1) as bigint)*86400+datediff(s,dateadd(day, datediff(day, 0, #d1), 0),#d1)
if you have ms sql server 2016+ use DATEDIFF_BIG function

my function with localization
CREATE FUNCTION UNIX_TIMESTAMP(#ctimestamp datetime)
RETURNS integer
AS
begin
return DATEDIFF(second,'1970-01-01',GETUTCDATE())+datediff(second,GETDATE(),#ctimestamp)
end
then i use value in js code
new Date(unixSec*1000)

Related

Convert varchar data to datetime in SQL server when source data is w/o format

How can I convert VARCHAR data like '20130120161643730' to DATETIME ?
CONVERT(DATETIME, '20130120161643730') does not work.
However, CONVERT (DATETIME, '20130120 16:16:43:730') works. I guess it needs data in correct format.
Is there a valid way that can be used to convert to DATETIME directly from unformatted data ?
My solution is :
DECLARE #Var VARCHAR(100) = '20130120161643730'
SELECT CONCAT(LEFT(#Var,8),' ',SUBSTRING(#var,9,2),':',SUBSTRING(#var,11,2),':',SUBSTRING(#var,13,2),':',RIGHT(#Var,3))
It works fine. However, I'm looking for a compact solution.
You can make it a little more compact by not forcing the dashes, and using STUFF instead of SUBSTRING:
DECLARE #Var VARCHAR(100) = '20130120161643730';
SET #Var = LEFT(#Var, 8) + ' '
+ STUFF(STUFF(STUFF(RIGHT(#Var, 9),3,0,':'),6,0,':'),9,0,'.');
SELECT [string] = #Var, [datetime] = CONVERT(DATETIME, #Var);
Results:
string datetime
--------------------- -----------------------
20130120 16:16:43.730 2013-01-20 16:16:43.730
DECLARE #var VARCHAR(100) = '20130120161643730'
SELECT convert(datetime,(LEFT(#var,8)+' '+SUBSTRING(#var,9,2)+':'+SUBSTRING(#var,11,2)+':'+SUBSTRING(#var,13,2)+':'+RIGHT(#var,3)))
The only possible way to convert this type of string to date time is to break it and then convert it to DateTime. Also, Concat doesnt work in MS SQL but "+".
Assuming this format is something you work with regularly, something more compact would be to create a UDF (user defined function) that parses the string into a valid datetime.
So something along the lines of:
create function dbo.ParseDate (#var varchar(max)) returns datetime as
begin
return (convert(datetime,(LEFT(#var,8)+' '+SUBSTRING(#var,9,2)+':'+SUBSTRING(#var,11,2)+':'+SUBSTRING(#var,13,2)+':'+RIGHT(#var,3))))
end
You could then select from that function like this:
select dbo.ParseDate('20130120161643730')
So any code that needed to reference the date would be more compact.

T-SQL 2008 Convert Date and time string to datetime

I have two columns in my table, one to capture time and one to capture date. Unfortunately, both are varchar(). I need to take the two fields, concatenate them together, and then convert them to datetime.
I am trying to accomplish that with this:
select CONVERT(datetime,(select txt_returned_date+' '+CONVERT(varchar(20),CONVERT(TIME,txt_time_returned))),126)
from table_name
I am getting this error message:
Conversion failed when converting date and/or time from character string.
The date is being captured as "20130308" as a string. Time is being captures as "4:27 PM" as a string
What I am doing here is converting the string of the time to TIME, then back to varchar. Then I am concatenating them together. This works by itself, but once I introduce the CONVERT(datetime) to the whole query, it is giving me the error.
Any help to try to accomplish this is helpful. Thanks!
You can concatenate the DATE and TIME values together once they have been converted to a DATETIME. Here's a sample to play with that shows concatenating a DATE column and a TIME column that have been stored as VARCHAR:
-- Set up some variables to test with
DECLARE #myTime TIME = GETDATE()
, #myDate DATE = GETDATE()
, #myTimeTxt VARCHAR(16)
, #myDateTxt VARCHAR(10);
-- Initialize your variables
SELECT #myTimeTxt = #myTime
, #myDateTxt = #myDate;
-- Display your separated values
SELECT #myDateTxt, #myTimeTxt;
-- Display your concatenated value
SELECT CAST(#myDateTxt AS DATETIME) + CAST(CAST(#myTimeTxt AS TIME) AS DATETIME);
You can use this option
DECLARE #date date = '20010101',
#time time = '01:01:01'
SELECT CAST(#date AS datetime) + #time
Result:2001-01-01 01:01:01.000
Demo on SQLFiddle
Are you using SQL 2012? If so you may be able to use the datetimedromparts function to achieve this. If not for this specific example, it's always good to know for the future :)
http://technet.microsoft.com/en-gb/library/hh213233.aspx

SQL: Using DATEADD with bigints

I have some SQL to convert javascript dates to SQL dates which works great. However, I've encoutered some data which is too large and is causing an exception:
Arithmetic overflow error converting expression to data type int
Here is the SQL in question:
DATEADD(MILLISECOND, cast(569337307200000 as bigint) % 1000, DATEADD(SECOND, cast(569337307200000 as bigint) / 1000, '19700101'))
I am running this on SQL Server 2008.
Just do the problematic DATEADD in two steps, starting with a coarser time unit (seconds, minutes, hours etc.), then dropping back to the fine grained one for the remainder.
Avoid going to the level of weeks and months though as that would require actual calendar calculations and we would prefer the system to handle that.
Example below needs to calculate a start time given a (possibly) large current duration in milliseconds.
-- large durations can overflow the integer argument needed for DATEADD
-- so do as two steps subtracting minutes (60000ms) and then remaining milliseconds.
DATEADD(ms, -large_duration_ms%60000, DATEADD(minute, -large_duration_ms/60000, GETDATE()))
One way I got around the Integer overflow issue was to subtract a more recent date from the microtime unix time stamp.
DATEADD(s, (CreationTimeStamp/1000-1384128000), '2013-11-11') AS CreateDate,
This will not fix the OP's problem because they will still overflow the max on the date column.
According to MSDN, in DATEADD (datepart , number , date )
number is an expression that can be resolved to an int that is added
to a datepart of date. User-defined variables are valid. If you
specify a value with a decimal fraction, the fraction is truncated and
not rounded.
Also notice that even if you give number as an integer, depending on your date & datepart, it could overflow the max range of the date which is 31-12-9999 for sql server 2008
Number has to be an integer. Here is a Test Demo
I had the same problem and I wanted to be meet the datetime range of mssql
Minimun datetime: 1753-01-01 00:00:00.000 (-6847804800)
Maximum datetime: 9999-12-31 23:59:59.997 (253402300799)
To achieve this the only solution I found was to loop to use DATEADD with int range values.
So based on this answer: https://stackoverflow.com/a/2904294/687490
CREATE FUNCTION dbo.fn_ConvertToBigDateTime (#Datetime BIGINT)
RETURNS DATETIME
AS
BEGIN
DECLARE #result datetime = Convert(datetime, '01/01/1970');
DECLARE #LocalTimeOffset BIGINT
,#AdjustedLocalDatetime BIGINT
,#MinIntValue INT
,#MaxIntValue INT
,#RemainingSeconds BIGINT;
-- define int limit
SET #MinIntValue = -2147483648;
SET #MaxIntValue = 2147483647;
-- compute the datetime with the offset
SET #LocalTimeOffset = DATEDIFF(second,GETDATE(),GETUTCDATE())
SET #AdjustedLocalDatetime = #Datetime - #LocalTimeOffset
-- going to the future
WHILE(#AdjustedLocalDatetime>#MaxIntValue)
BEGIN
SET #AdjustedLocalDatetime = #AdjustedLocalDatetime - #MaxIntValue;
SELECT #result = Convert(datetime, dateadd(ss, #MaxIntValue,#result));
END
-- going back in the past
WHILE(#AdjustedLocalDatetime<#MinIntValue)
BEGIN
SET #AdjustedLocalDatetime = #AdjustedLocalDatetime - #MinIntValue;
SELECT #result = Convert(datetime, dateadd(ss, #MinIntValue,#result));
END
RETURN (SELECT DATEADD(second,#AdjustedLocalDatetime, #result))
END;
You can then test the function with :
select dbo.fn_ConvertToBigDateTime(-6847804800) as 'min datetime',
dbo.fn_ConvertToBigDateTime(253402300799) as 'max datetime'
Hope it will help.
You can try converting the millis to days, add the days to beginning of EPOCH, and add the ms part to the date at the end. The problem is that you were trying to convert millis to seconds, which can still be too large number for INT for larger dates.
DATEADD(MILLISECOND,
CAST(myLongDateMs AS BIGINT) % 86400000,
DATEADD(day,
CAST(myLongDateMs AS BIGINT) / 86400000,
'19700101'
)
)
I faced this problem too. In my sql statement, the error occurred when the date time value is null.
My solution is to check whether the date time value is null using "CASE When". Only running the arithmetic when it is not null, and the problem solved.

convert string to datetime in function SQL Server

I have been writing a user-defined function in SQL Server:
It looks like this :
CREATE FUNCTION FormatDate(#fromtime nvarchar(50))
RETURNS DATETIME
AS
BEGIN
DECLARE #tempfrom datetime
DECLARE #tempto nvarchar(50)
set #tempfrom = Convert(datetime, #fromtime, 100)
RETURN #tempfrom
END
select dbo.FormatDate('08/17/2010 4:30')
When I try to run this, I get the following error:
Conversion failed when converting the nvarchar value '08/17/2010 4:30' to data type int.
What am I doing wrong?
The 100 you're specifying in the convert is used to format when you're selecting data, not to format the storage of data.
Datetime is just stored as datetime - that's it (i mean, dependent on your SQL settings, it might be MM/DD/YYYY or DD/MM/YYYY).
But if you just do this:
set #tempfrom = Convert(datetime, #fromtime)
it's now a datetime, which you can convert to your desired formatting by wrapping it in another convert:
convert(varchar, convert(datetime, #fromtime), 100)
Why are you using style 100?
CREATE FUNCTION dbo.FormatDate -- schema prefix always!
(
#fromtime VARCHAR(50) -- varchar
)
RETURNS DATETIME
AS
BEGIN -- don't need variables anywhere
RETURN(CONVERT(DATETIME, #fromtime));
END
GO

How can I transform this Lambda Expression into SQL statement?

I have a lambda expression that has this:
Convert.ToDateTime(a.startTime).TimeOfDay >= Convert.ToDateTime(startTime).TimeOfDay
But, I have to create a procedure in SQL Server and how should be the statement above to SQL statement?
I've tried to use some kinda 'convert(startime, getdate(),8) but it didn't work.
And I forgot to say that 'startTime' is a DateTime field and I'm trying to compare only the time part (forget about the date part).
Thanks!!!
From here:
CREATE FUNCTION dbo.TIMEVALUE
(
#Datetime datetime
)
/*******************************************************************************
* AUTHOR: Luciano Evaristo Guerche *
*******************************************************************************/
RETURNS datetime
AS
BEGIN
RETURN (#Datetime - CAST(ROUND(CAST(#Datetime AS float), 0, 1) AS datetime))
END
GO
Have you tried:
CAST(starttime as time)
Have a look at this for more detail time (Transact-SQL)