SQL Server UTC timestamp - sql-server

I have stored procedure which inserts data into some table. There is a column say pick up time (datatype datetime). Now the time is in datetime format I want the stored procedure to store datetime to UTC zone timing.
How to do it in the stored procedure?

There are several ways to get the UTC time. Which you use depends on what you need:
SELECT GETUTCDATE(), --datetime
SYSUTCDATETIME(), --datetime2(7)
SYSDATETIMEOFFSET() AT TIME ZONE 'UTC'; --datetimeoffset(7)

This is simple to achieve using GETUTCDATE() as shown:
SELECT GETUTCDATE()
Output:
2021-06-02 12:55:01.213
As per the description in the docs:
Returns the current database system timestamp as a datetime value. The
database time zone offset is not included. This value represents the
current UTC time (Coordinated Universal Time). This value is derived
from the operating system of the computer on which the instance of SQL
Server is running.

SELECT GETDATE() AS PickUpTime, GETUTCDATE() AS UTCTime

Use GETUTCDATE() function in the Insert statement inside your stored procedure:
Insert into MyTable (PickUp_Col)
values (GETUTCDATE() )

Related

Time difference calculation based on timezone and offset

We transfer data from Oracle SQL to SQL Server in the near real-time data warehouse. (Oracle is a transactional database) The time changes twice a year for the data we use. We have been having issues when calculating DateTime differences and I have to work on a short-term and long-term solutions where I need advice.
New data coming in :
I can create tables from scratch and use datetimeoffset data field for all the time variables. Would this
display dates in SQL Server queries in the local time zone and save them in their actual UTC time? And when I
calculate the differences, would it give the correct difference?
Existing data without offset information:
I already have data converted into the current timezone. We have 2 timezones AEST and AEDT.
When we calculate time differences for KPIs it gives incorrect times. Any ideas on how it can be resolved?
Can creating a function that converts the dates and times into UTC and subtracts the difference and returns the value would work?
An example below :
DECLARE #startdate DateTime = '2022-10-01 23:13:00.000'; --UTC 2022-10-01 13:13:00.00
DECLARE #enddate DateTime = '2022-10-02 12:08:00.000' --UTC 2022-10-02 01:08:00.00
select CAST((#enddate - #startdate) as time(0)) 'Difference'
Time difference: 12:55:00
Actual Time Difference: 11:55:00
For your example, if you include the time zone info with the data, the date calculations work out
DECLARE #startdate datetimeoffset(0) = '2022-10-01 23:13:00 +10:00'; --UTC 2022-10-01 13:13:00.00
DECLARE #enddate datetimeoffset(0) = '2022-10-02 12:08:00 +11:00' --UTC 2022-10-02 01:08:00.00
declare #minutes int = datediff(minute, #startdate, #enddate);
select #startdate at time zone 'utc',
#enddate at time zone 'utc';
select [hours] = #minutes / 60,
[minutes] = #minutes - 60 * (#minutes / 60)
To address the existing data, you can do a one-time conversion to datetimeoffset by running it through at time zone with the appropriate time zone name. In my example above, I used UTC but you can find all of the supported time zones in sys.time_zone_info.
As to your first question about the internal storage format and display, I'm not sure if it uses UTC internally or not. As to display, it will, by default, output them with the time zone that you stored them with. That is, if you stored a given value with +10:00 as the offset, that's how it will display. You can convert via methods already described above or with switchoffset(). Lastly, if it matters, you can get just the offset with datepart noting that it returns the offset in number of minutes (to conform with datepart needing to return an int).

Snowflake: how to get the current Unix epoch timestamp

How can I get the current Unix epoch timestamp in Snowflake? I could not find any documentation on the same
Using DATEDIFF:
SELECT DATEDIFF(second, '1970-01-01'::DATE, CURRENT_TIMESTAMP());
or DATE_PART:
SELECT DATE_PART(epoch_second, CURRENT_TIMESTAMP());
Supported Date and Time Parts:
epoch_second
epoch_millisecond
epoch_microsecond
epoch_nanosecond
This solution is timezone independent, no math needed:
alter session set timezone = 'US/Eastern';
select date_part(epoch_second, current_timestamp());
-- 1637194610
alter session set timezone = 'America/Los_Angeles';
select date_part(epoch_second, current_timestamp());
-- 1637194621
Note that current_timestamp() returns what you want, while current_date() only returns the day (without a time component).

currenttimestamp with timezone in sql server

What is the sql server query to retrieve current time stamp with us/central time zone?
You need both local and remote timezones, so Oracle can calculate the difference e.g.
SELECT FROM_TZ(CAST(sysdate AS TIMESTAMP), 'America/New_York')
AT TIME ZONE 'America/Los_Angeles'
FROM DUAL;
30.10.14 08:45:08,000000000 AMERICA/LOS_ANGELES
and
SELECT FROM_TZ(CAST(sysdate AS TIMESTAMP), 'America/New_York')
AT TIME ZONE 'America/Chicago'
FROM DUAL;
30.10.14 10:46:17,000000000 AMERICA/CHICAGO
You can get the list of timezone names with this:
SELECT tzname, tzabbrev FROM V$TIMEZONE_NAMES;
so you can do this:
SELECT FROM_TZ(CAST(sysdate AS TIMESTAMP), 'America/New_York')
AT TIME ZONE 'US/Central'
FROM DUAL;
assuming you are in New York.
If this is for SQL Server 2008 or above, this will provide the time at a specific timezone offset. I don't know if you can provide a timezone name, and using this method, you'll have to handle daylight savings yourself.
declare #dt datetimeoffset = switchoffset(convert(datetimeoffset, getutcdate()), '-06:00')
select getutcdate() as utc, #dt as [datetimeoffset], cast(#dt as datetime) as [datetime]
Time zone support was added with SQL Server 2016. You can now do this:
SELECT SYSDATETIMEOFFSET() AT TIME ZONE 'Central Standard Time'
Note that the identifier Central Standard Time is the Windows time zone ID for Central Time in US and Canada. It is inclusive of both CST and CDT.

What date format is this? (001281379300724)

Need to convert this timestamp (001281379300724) to YYYY-MM-DD hh:mm:ss format in SQL Server, if possible. Any suggestions?
This presumes the timestamp is ms since UNIX epoch. It only converts to the nearest second, but you could add ms to it(see below). It has to use two steps since dateadd requires an int. First add minutes by dividing by 60000, then add seconds.
DECLARE #yournum bigint
SET #yournum = 1281379300724
SELECT DATEADD(ss, (#yournum / 1000)%60 , (DATEADD(mi, #yournum/1000/60, '19700101')))
Gives
2010-08-09 18:41:40.000
To get ms precision: (yuck, probably a better way)
DECLARE #yournum bigint
SET #yournum = 1281379300724
SELECT DATEADD(ms, (#yournum%1000),DATEADD(ss, (#yournum / 1000)%60 , (DATEADD(mi, #yournum/1000/60, '19700101'))))
Gives
2010-08-09 18:41:40.723
The simple answer is that if this is a SQL timestamp column (a.k.a rowversion), you can't. Per the documentation for the type:
Each database has a counter that is incremented for each insert or
update operation that is performed on a table that contains a
rowversion column within the database. This counter is the database
rowversion. This tracks a relative time within a database, not an
actual time that can be associated with a clock.
...
The Transact-SQL timestamp data type is different from the timestamp
data type defined in the ISO standard.
You can get slightly closer this way:
SELECT DATEADD(MINUTE, 1281379300724/1000/60, '19700101')
Result:
2010-08-09 18:41:00.000

Converting normal datetime to a time zone in sql server 2008

I have a column which is of datetime data type. It contains few entries. So while getting the value from the select statement I want to output with Time zone. Please help me
for example
2007-05-08 12:35:29.1234567 +05:30 (GMT)
Cast it to dtaetimeoffset like
select CAST(dt as datetimeoffset) from test
EDIT:
you can then use SWITCHOFFSET to get into the specified timezone. For your example
select switchoffset(CAST(dt as datetimeoffset),'+05:30') from test
Results in 2011-11-24 23:26:30.0600000 +05:30

Resources