Thursday, February 03, 2022

How To: Detect Daylight Savings Time in Snowflake

 I created this function to easily determine if a date is in Daylight Savings Time or Standard Time.    


CREATE OR REPLACE FUNCTION IS_DAYLIGHT_SAVINGS(DATE TIMESTAMP)
  RETURNS VARCHAR
  LANGUAGE JAVASCRIPT
AS
$$
// STANDARD TIME IS Calc SECOND Sunday in MARCH
var standardMonth = new Date(DATE.getFullYear(), 2);
var standardMonthFirstDayType = standardMonth.getDay();
var standardDaysToAdd = 7 + (8 - (standardMonthFirstDayType % 6))   ; // Its +7 and +1 to Account for day one in month
var standardDate = new Date(DATE.getFullYear(), 2, standardDaysToAdd, 2);  
// DAYLIGHT SAVINGS TIME IS Calc FIRST Sunday in NOVEMBER
var dayLightMonth = new Date(DATE.getFullYear(), 10);
var dayLightMonthFirstDayType = dayLightMonth.getDay();
var daylightDaysToAdd = (8 - (standardMonthFirstDayType % 6)) ; //  Its +7 and +1 to to Account for day one in month
var daylightDate = new Date(DATE.getFullYear(), 10, daylightDaysToAdd, 2);  
//DST Test
if (DATE >= daylightDate || DATE < standardDate) {
    return 0;
}
else {
    return 1;
}
$$;

SELECT IS_DAYLIGHT_SAVINGS('2021-11-07 02:00') AS NOV, 
       IS_DAYLIGHT_SAVINGS('2021-03-14 02:00') AS MARCH  ;
SELECT IS_DAYLIGHT_SAVINGS('2021-11-07 01:59') AS NOV, 
       IS_DAYLIGHT_SAVINGS('2021-03-14 01:59') AS MARCH  ;

No comments: