Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you determine Daylight Savings Time in VBA?

What function will let us know whether a date in VBA is in DST or not?

like image 473
Lance Roberts Avatar asked Sep 25 '08 00:09

Lance Roberts


2 Answers

For non-current dates (DST 2007+):

First, you need a function to find the number of specific weekdays in a month:

Public Function NDow(Y As Integer, M As Integer, _
                N As Integer, DOW As Integer) As Date  

' Returns Date of Nth Day of the Week in Month  

NDow = DateSerial(Y, M, (8 - Weekday(DateSerial(Y, M, 1), _
              (DOW + 1) Mod 8)) + ((N - 1) * 7))  

End Function  

Then, you can check for the DST day versus the following function calls:

Fall: NDow(Year(newdate), 11, 1, 1)
Spring: NDow(Year(newdate), 3, 2, 1)

For the current date:

Call the Windows API function GetTimeZoneInformation, and it will return an enum (integer) with the status.

I got the code for this from Chip Pearson's great Excel site.

Pearson's site

like image 178
Lance Roberts Avatar answered Oct 23 '22 16:10

Lance Roberts


For anyone wondering how to account for daylight saving time in Europe (central europe time), I modified the script from Chip Pearson. The last sunday of March (2 AM to 3 AM) and October (3 AM to 2 AM) are the days when the hour switching occurs.

Following code is the click event of a button in Excel:

Dim dates As String
dates = "A1:A20"

For Each c In Worksheets("Sheet1").Range(dates).Cells
    If (IsDateWithinDST(c.Value)) Then
        c.Value = DateAdd("h", 1, c.Value)
    End If
Next

The module containing the necessary methods are to be found here.

More info on DST in Europe.

like image 4
Pieter Heemeryck Avatar answered Oct 23 '22 16:10

Pieter Heemeryck