Convert date column to new UTC date column - sql

I wrote the following query on a SQL Server DB to convert a datetime column to a UTC date column.
select datetime
, dateadd(minute,-datepart(tz,datetime),datetime) datetime_dt_utc
from table1
But I get the same same datetime for both columns.
What do I have to change to make it work?

Please try this:
DATEADD(hh, DATEDIFF(hh, GETDATE(), GETUTCDATE()), datetime)
The GETDATE() will return the current time
The GETUTCDATE() will retunr the current UTC time
The DATEDIFF function will calculate the difference between this two datetimes in hours
The DATEADD function will add this hours to your current datetime.
Another way is via usign the AT TIME ZONE
SELECT datetime AT TIME ZONE 'UTC' from table1
You can check your time zone with:
select CURRENT_TIMEZONE ( )
And use this:
SELECT datetime AT TIME ZONE 'Pacific Standard Time' AT TIME ZONE 'UTC'
from table1
If you are in 'Pacific Standard Time' timezone

Related

How can I add/subtract the offset value into datetime and return new datetime value in SQL?

I am new to SQL and I want to add/subtract the offset value into the DateTime and return new date.
Currently, I am using this
SELECT
GETUTCDATE() AS UTCDate,
GETUTCDATE() AT TIME ZONE 'Eastern Standard Time'
which returns these values:
Current Result : 2021-12-28 07:19:39.320 -05:00
Expected Result : 2021-12-28 02:19:39.320
How can I achieve this? Any help would be appreciated. Thanks
You can use DATEADD and DATEDIFF function:
SELECT GETUTCDATE() AS UTCDate, GETUTCDATE() AT TIME ZONE 'Eastern
Standard Time' ,
DATEADD(MINUTE, DATEDIFF(MINUTE ,GETUTCDATE(), GETUTCDATE() AT TIME ZONE
'Eastern Standard Time')*-1, GETUTCDATE())
GETUTCDATE() returns datetime type. You can use SYSDATETIMEOFFSET() instead to get datetimeoffset and convert it to a desired timezone.
SELECT
SYSDATETIMEOFFSET() AS UTCDate_with_timezone,
SYSDATETIMEOFFSET() AT TIME ZONE 'Eastern Standard Time';
When AT TIME ZONE operator is applied to datetime value it does not change the value, you just inform the system what is the timezone. And this timezone will be just appended to the value.

Proper way of getting rows since a date accounting for DST?

I have a datetime column, changedate, that I need to use to get rows that have changed in the last week since 1PM. This column is unfortunately in local time (EST). The server is Microsoft SQL Server 2016.
Here is the query I have now:
DECLARE #since datetime = DATEADD(week,-1,SMALLDATETIMEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), DAY(GETDATE()), 13, 0)) AT TIME ZONE 'Eastern Standard Time'
SELECT * FROM table WHERE changedate AT TIME ZONE 'Eastern Standard Time' >= #since
Since I'm using AT TIME ZONE for both the column and #since, will this properly account for DST changes? That's my understanding per the documentation I've found, but I'm not 100% sure if that's how it works or if I'm missing something.
First, figure out the time you're wanting to compare against:
-- Get the current date in the given time zone
DECLARE #today date = convert(date, sysdatetimeoffset() AT TIME ZONE 'Eastern Standard Time')
-- Get the date one week ago
DECLARE #dateOneWeekAgo date = DATEADD(week, -1, #today)
-- Join the date with the desired time (local to the same time zone)
DECLARE #since datetime = convert(datetime, #dateOneWeekAgo) + convert(datetime, timefromparts(1, 0, 0, 0, 0))
Then just compare it:
SELECT * FROM table WHERE changedate >= #since
That assumes your changedate field is a datetime or datetime2. If it's a datetimeoffset, you should first convert the target value to a datetimeoffset in the same time zone and use that instead:
DECLARE #sinceDTO datetimeoffset = #since AT TIME ZONE 'Eastern Standard Time'
Regarding the approach you gave in the question, there two issues:
getdate() gives the time based on the server's local time zone. It's possible that it's not the same day in Eastern Time.
You should never apply a function (whether an intrinsic like AT TIME ZONE or something else) against a table field in a where clause, because it makes the query non-sargable. In other words, SQL would have to scan the entire table, rather than using an index. The bigger the table, the slower the query would take.

DateTime conversion and comparison in SQL Query

I have a sql query for pulling a report from a table. The idea is to pull the sum of counts, grouped by day of the week, in the local timezone. Dates in the table are stored in UTC.
SELECT (SUM(t.di1) + SUM(t.di2) + SUM(t.di3) + SUM(t.di4)) AS [ScanCount],
DATEPART(WEEKDAY, t.LocalTime) AS [weekday]
FROM (SELECT di1,
di2,
di3,
di4,
CreatedOnUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS LocalTime
FROM tableName
WHERE DeviceId = 649754) t
WHERE t.LocalTime > '03/16/2020 00:00'
AND t.LocalTime < '03/16/2020 23:59:59'
GROUP BY DATEPART(WEEKDAY, t.LocalTime)
ORDER BY DATEPART(WEEKDAY, t.LocalTime);
A query like this should only return a single day of the week count, but it returns 2 days. This obviously has something to do with the difference in time zones, whereas the UTC time contains dates from both 3/15 and 3/16. It seems that the conversion from UTC to Pacific Time works in the output but the UTC values are used in the where clause. How can I do this comparison to the new converted datetimes and not to the original UTC times?
Comparison between datetimeoffset and string literal works in UTC.
Simplest solution will be to convert datetimeoffset to datetime2.
Modify your inner query to:
cast(CreatedOnUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' as datetime2(0)) AS LocalTime

Compare datetimeoffset with timezone SQL

I have a date emp_date which is of type datetime offset. This date is saved correctly in the database.
I want to retrieve all data having the date emp_date less than the actual time, including time zone.
For example, if the emp_date is as below:
2019-10-25 23:44:09.5798885 +14:00
And I am in a time zone of +2, then the data having the above date should not be retrieved.
Any idea of how to do this?
I want to pass the timezone of the user as parameter.
https://dzone.com/articles/dates-and-times-in-sql-server-at-time-zone
pass the needed time zone as parameter, then we can convert to the needed time zone.
DECLARE #TimeZone varchar(50)
SET #TimeZone = 'Central European Standard Time'
SELECT getdate() AT TIME ZONE #TimeZone AS date
SELECT getdate() AT TIME ZONE 'Central European Standard Time' AS date

SQL Server AT TIME ZONE

Using AT TIME ZONE is there a way to get my UTC Time without the 00:00 AT The end without using a LEFT in my query.
im doing this:
SELECT GETDATE() AT TIME ZONE 'EASTERN standard time' at time zone 'UTC'
Answer: 2018-03-05 15:08:00.930 +00:00
and trying to see if there is a better way other than doing
SELECT LEFT(GETDATE() AT TIME ZONE 'EASTERN standard time' at time zone 'UTC',23)
I would say declare it as variable and get datetime info from the datetimeoffset
Convert to datetime will do the trick
DECLARE #MyUtctime DATETIMEOFFSET
SET #MyUtctime = (
SELECT getdate() AT TIME ZONE 'EASTERN standard time' at TIME zone 'UTC'
)
SELECT CONVERT(DATETIME, #MyUtctime, 1)
SELECT getdate()
The following code will output your desired results:
CONVERT(VARCHAR, CONVERT(DATETIME, <DateField> AT TIME ZONE 'Eastern Standard Time' AT TIME ZONE 'UTC'), 100) AS [LocalDateTime]
If your EST date was '2018-03-22 22:48:24.893' the output UTC date would be 'Mar 22 2018 2:48AM'.