How to convert Datetime to timestamp? (SQL SERVER)

Asked

Viewed 269 times

0

Today I have the following situation, I need to send the current date and time of the request in an int format, as image below

inserir a descrição da imagem aqui

Below are some attempts I made, but when testing the conversion to date for validation of the result, returned an inconsistent date.

cast(GETDATE() as bigint) CAST((convert(datetime,getdate(),108))

1 answer

1


Try some tests with the script below:

declare @DataIni datetime;
declare @Tempo int;
declare @Data datetime;

set @DataIni = dateadd(hour, datediff(hour, getutcdate(), getdate()), '19700101');

set @Data = '20210114 01:16:58';

set @Tempo = datediff(second, @DataIni, @Data);

select @Tempo, dateadd(second, @Tempo, @DataIni)

Obs: 01/01/1970 UTC/GMT is the standard starting date for the calculation

I hope it helps

  • Imex, how can I use only the column that returned the entire data? put an alias for it?

  • 1

    I don’t know if I understand this correctly, but try something like this: select
 datediff
 (second, 
 dateadd(hour, datediff(hour, getutcdate(), getdate()), '19700101'), 
 getdate()) as Tempo

  • That’s right, perfect!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.