Created
April 9, 2025 02:51
-
-
Save katydorjee/75b02a5401764a16873c7fc947da264c to your computer and use it in GitHub Desktop.
SQL Query to Convert from CST to AEST or AEDT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT | |
CASE | |
/* Check if the current date is between the first Sunday of October and the first Sunday of April (AEDT period) */ | |
WHEN GETDATE() >= | |
/* First Sunday in October */ | |
DATEADD(DAY, 1 - DATEPART(WEEKDAY, DATEFROMPARTS(YEAR(GETDATE()), 10, 1)) + 7 * (1), DATEFROMPARTS(YEAR(GETDATE()), 10, 1)) | |
AND GETDATE() < | |
/* First Sunday in April */ | |
DATEADD(DAY, 1 - DATEPART(WEEKDAY, DATEFROMPARTS(YEAR(GETDATE()), 4, 1)) + 7 * (1), DATEFROMPARTS(YEAR(GETDATE()), 4, 1)) | |
THEN DATEADD(HOUR, 17, GETDATE()) /* AEDT (UTC+11) */ | |
ELSE DATEADD(HOUR, 16, GETDATE()) /* AEST (UTC+10) */ | |
END AS LocalDateTime |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation:
GETDATE(): This function gets the current date and time from the SQL server (in CST).
First Sunday in October:
DATEFROMPARTS(YEAR(GETDATE()), 10, 1): Generates the date for October 1st of the current year.
DATEPART(WEEKDAY, ...): This function determines which weekday October 1st falls on.
The formula DATEADD(DAY, 1 - DATEPART(WEEKDAY, ...) + 7 * (1), ...) adjusts the date to find the first Sunday in October.
First Sunday in April:
DATEFROMPARTS(YEAR(GETDATE()), 4, 1): Generates the date for April 1st of the current year.
Similar to October, it adjusts the date to find the first Sunday in April.
CASE:
Checks if the current date (GETDATE()) is between the first Sunday of October and the first Sunday of April.
If it is, it adds 17 hours (CST to AEDT).
Otherwise, it adds 16 hours (CST to AEST).
How It Works:
If the current date is between the first Sunday in October and the first Sunday in April, the query adds 17 hours to convert CST (UTC-6) to AEDT (UTC+11).
If the current date is outside that range (i.e., from the first Sunday in April to the first Sunday in October), the query adds 16 hours to convert CST to AEST (UTC+10).
Example:
During AEDT (October to April):
If today is October 5th, 2025, the query will add 17 hours to CST and return the converted time in AEDT (UTC+11).
Outside AEDT (April to October):
If today is July 10th, 2025, the query will add 16 hours to CST and return the converted time in AEST (UTC+10).