2

Converting Azure UTC DateTime to User Defined Locale and DateTime

 1 year ago
source link: https://jamiemaguire.net/index.php/2022/10/29/converting-azure-utc-datetime-to-user-defined-locale-and-datetime/?utm_campaign=converting-azure-utc-datetime-to-user-defined-locale-and-datetime
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Recently I had to write stored procedures to query records in an Azure SQL database.

Each record contained a DateTime field that that lets Azure Web Jobs know if a record should be processed.

We’ll call this field DateToRun.

Problem

When running queries for these records, DateToRun was compared against the SQL command GETDATE() in the WHERE clause to determine if a record should be processed.

The problem with this however was that each user in the system can set their own timezone in the application.

This meant the WHERE clause would often fail as their timezone wasn’t aligned with the locale in Azure SQL.

The Solution

The solution for this is to use SWITCHOFFSET and TZOFFSET, passing in the users timezone setting, and applying this to GETDATE().

For example:

WHERE [mytable].DateToRun >= CONVERT(datetime, SWITCHOFFSET(GETDATE(), DATEPART(TZOFFSET,GETDATE() AT TIME ZONE GMT Standard Time)))

Using this applies the correct datetime offset to the DateToRun field.

This meant the WHERE clause would evaluate correctly and process records at the time aligned with the users timezone settings.

Example

Here we have a sample query:

declare @timezone nvarchar (255);
set @timezone = 'GMT Standard Time';
select GETDATE() AzureDateTime_UTC, CONVERT(datetime, SWITCHOFFSET(GETDATE(), DATEPART(TZOFFSET,GETDATE() AT TIME ZONE @timezone))) UserDateTime_GMT

And the results:

The output UserDateTime_GMT field can then be used by other business areas or logic in the application

Resources

Learn and read more about SWITCHOFFSET here and TZOFFSET here.

JOIN MY EXCLUSIVE EMAIL LIST
Get the latest content and code from the blog posts!
I respect your privacy. No spam. Ever.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK