GETUTCDATE() and Time Zone (SQL Server) - sql-server

I want to add my time zone with the function GETUTCDATE() in SQL Server. I searched several times, but did not found any relevant solution. Thanks in advance.

only for sql 2016, it takes into account daylight savings.
CREATE FUNCTION GetBelgiumTime
(
)
RETURNS datetime2
AS BEGIN
declare #dateoffset datetimeoffset
SET #dateoffset = convert(VARCHAR(2000),(SELECT GETUTCDATE() AT TIME ZONE 'Central European Standard Time'),126 )
declare #date datetime2
set #date = convert(datetime2, LEFT(#dateoffset,28),126)
set #date = DATEADD(HOUR, convert(int,LEFT(RIGHT(#dateoffset,5), 2)), #date)
RETURN #date
END
select dbo.GetBelgiumTime() as BelgiumDateAndTime

From SQL Server 2016 forward (and Azure SQL DB), you can do this:
SELECT SYSDATETIMEOFFSET() AT TIME ZONE #tz
where #tz is a valid Windows time zone identifier, such as 'Pacific Standard Time', 'Central European Standard Time', etc.
However, if you are on an older version of SQL Server, or prefer to use IANA time zone identifiers, you can use my SQL Server Time Zone Support project to do the following:
SELECT Tzdb.UtcToLocal(GETUTCDATE(), #tz)
where #tz is an IANA standard time zone name, such as 'America/Los_Angeles' or 'Europe/Budapest'.

Use GETDATE() instead GETUTCDATE(). see this link

You can try to use switchoffset like this:
select switchoffset(CAST(myDate as datetimeoffset),'+05:30') from someTable
Instead of '+05:30' you can specify your timezone value.
If you want to use the timezone with GETUTCDATE() then simply add it like this
select cast(GETUTCDATE() as varchar(20)) + '+5:30'
and if you want to keep it as date only then
select switchoffset(CAST(GETUTCDATE() as datetimeoffset),'+05:30')

Related

SQL Server UTC timestamp

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() )

How to return Datetimeoffset in SQL view using at time zone

is it possible to return a value from a table that is of type datetime as datetimeoffset in a view using AT TIME ZONE?
When I try this with
CREATE VIEW TESTVIEW AS
SELECT appointment_start AT TIME ZONE 'central european standard time' AS x
FROM dbo.Appointments
the result is as expected, but when I open the view in SQL Management Studio, I get the message 'Unable to parse query text.'
The same when I try something like
SELECT TODATETIMEOFFSET(appointment_start, DATEPART(tz, appointment_start AT TIME ZONE 'central european standard time')) as y
FROM dbo.Appointments
How do I get the datetime value converted to a datetimeoffset using AT TIME ZONE in an SQL view?
EDIT:
When I additionally select another column from the table, I also get the expected result, but the SQL Management Studio complains
SELECT
id, appointment_start AT TIME ZONE 'central european standard time' AS x
FROM dbo.Appointments
Error in SELECT clause: expression near 'TIME'.
Missing FROM clause.
Error in list of function arguments: 'AT' not recognized.
Unable to parse query text.
Thanks a lot
For whom it may concern:
Solved it by using an SQL function.
Maybe not the most elegant way but it seems to work.
CREATE FUNCTION [dbo].[TODATETIMEOFFSETINTIMEZONE]
(
#Date AS DateTime,
#Timezone as NVARCHAR(100)
)
RETURNS DateTimeoffset
AS
BEGIN
DECLARE #NewDate As DateTimeoffset
SELECT #NewDate = #Date AT TIME ZONE #Timezone
RETURN #NewDate
END
GO
And in the SQL View
SELECT
id,
TODATETIMEOFFSETINTIMEZONE(appointment_start, N'W. Europe Standard Time') AS appointment_start
FROM dbo.Appointments

Query epoch time using SQL Server to find date range

I have to query an SQL Server database and the table's values use Epoch time (an int. Here's an example - 1438005018). I am wondering how I can write a query so that I can say the following...
select
*
from
tablename
where
epochdate between 'yesterday at 12:00' and 'today at 12:00' --this is the part I'm not sure about.
Ideally, if it's easy, I'd like the query to use non-epoch logic as Epoch time confuses the crap out of me. Maybe there's a quick way of converting in SQL Server?
I posted a link above in the comments that may be a more practical solution if you're able to deploy functions in the database you're working with, but if you're only able to query, this is an option to try as well (this assumes SQL Server 2008 and above):
declare #todayepoch bigint, #yesterdayepoch bigint;
select #todayepoch =
cast((cast(dateadd(hour, 12,
cast(cast(sysutcdatetime() as date) as datetime)) as decimal(24,10))
- cast(cast('1970-01-01' as datetime) as decimal(24,10)))
*60.0*60.0*24.0 as int), -- + 18000, --Eastern time
#yesterdayepoch =
cast((cast(dateadd(hour, -12,
cast(cast(sysutcdatetime() as date) as datetime)) as decimal(24,10))
- cast(cast('1970-01-01' as datetime) as decimal(24,10)))
*60.0*60.0*24.0 as int) -- + 18000 --Eastern time
select #todayepoch, #yesterdayepoch
select
*
from
tablename
where
epochdate between #yesterdayepoch and #todayepoch
I used UTC above as a presumption of comparing based on UTC times, but you could also compare to your time zone, with the appropriate addition/subtraction of your time zone difference in seconds (e.g., add 18000 to each variable to get noon in Eastern Standard Time).
You can test your results by using http://www.epochconverter.com/ to compare your values in your variables.
You query would look like the following:
DECLARE #dt_from DATETIME;
DECLARE #dt_to DATETIME;
SELECT
#dt_from=DATEADD(HH,-12,CAST(FLOOR(CAST(GETUTCDATE() AS FLOAT)) AS DATETIME)), -- strip time of current UTC date/time, and subtract 12 hrs
#dt_to=DATEADD(HH,+12,CAST(FLOOR(CAST(GETUTCDATE() AS FLOAT)) AS DATETIME)); -- strip time of current UTC date/time, and add 12 hrs
SELECT
*
FROM
tablename
WHERE
epochdate BETWEEN DATEDIFF(s,'1970-01-01',#dt_from) AND DATEDIFF(s,'1970-01-01',#dt_to);

Sql Server Convert between UTC-0 string dates and the server local TimeZone

When I execute the following, when the server's TimeZone is +01:00:
Convert(datetime, '2015-02-10T23:00:00Z', 127)
The result is:
10.02.2015 23:00:00
That is the Date at UTC-0. My expected value would be 11.02.2015 00:00:00, that is the date converted to the server's TimeZone.
Convert function doesn't convert time to UTC. It just simply changes the format of the input string. Here is what you need to do.
Find difference in hours between server local time and UTC time:
DECLARE #hour INT
SELECT #hour = DATEDIFF(HOUR, GETUTCDATE(), GETDATE())
Add the difference to the date you're trying to convert:
SELECT CONVERT(DATETIME, DATEADD(hour, #hour, '2015-02-10T23:00:00Z'), 127)
If you know your timezone difference in hours and you know that it's unlikely to be changed, then use a shorter version:
SELECT CONVERT(DATETIME, DATEADD(hour, -1, '2015-02-10T23:00:00Z'), 127)
You shouldn't really depend on the time zone setting of a server. However, if you have a specific time zone in mind, you could use my SQL Server Time Zone Support project.
After installation:
SELECT Tzdb.UtcToLocal('2015-02-10T23:00:00Z', 'Europe/Paris')
Choose a time zone from the list here.

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.

Resources