Check if Daylight Saving Time (DST) is in effect with Julia

Viewed 135

I need to convert from epoch times to date time strings and viceversa. Time string is formatted as YYYY/month/day HH:MM:SS and represents the local time.

How to get if DST is in effect?

const CSV_DATE_FORMAT = "%Y/%m/%d %H:%M:%S"

function ts(datetime::String)
    ts = Libc.strptime(CSV_DATE_FORMAT, datetime)
    # how to check if DST in is effect ???
    return Int(round(time(ts)))
end


function datetime(ts::Int64, fmt::String = "%Y/%m/%d %H:%M:%S")
    dt = Libc.TmStruct(ts)
    # if daylightsaving()
    #     ts.isdst = 1 
    # else
    #     ts.isdst = 0
    # end
    Libc.strftime(fmt, dt)
end

How do I check if Daylight Saving Time is in effect?

1 Answers

I wouldn't use Libc at all here; the Julia standard library Dates in conjunction with TimeZones package is far more functional and featureful. First, parse your date as a timezoneless Date:

julia> using Dates, TimeZones

julia> format = dateformat"Y/m/d H:M:S"
dateformat"Y/m/d H:M:S"

julia> dt = DateTime("2020/10/26 11:08", format)
2020-10-26T11:08:00

Then append the local time zone:

julia> zdt = ZonedDateTime(dt, localzone())
2020-10-26T11:08:00-04:00

Finally, you can ask if there will be any future transitions — and what they are:

julia> show_next_transition(zdt)
Transition Date:   2020-11-01
Local Time Change: 02:00 → 01:00 (Backward)
Offset Change:     UTC-5/+1 → UTC-5/+0
Transition From:   2020-11-01T01:59:59.999-04:00 (EDT)
Transition To:     2020-11-01T01:00:00.000-05:00 (EST)

Note that the concept of "Daylight Savings" isn't explicitly encoded into a timezone — there simply exist variable timezones that change which constant offset they're in at given times. You can see in the above output that I'm currently in UTC-4, but will be switching to UTC-5 on Sunday.

So if I wanted a simple function that asked if there is an offset from my normal timezone, it'd look something like this:

julia> is_offset(zdt::ZonedDateTime) = zdt.zone.offset.dst != Second(0)

julia> is_offset(ZonedDateTime(dt, tz"America/New_York"))
true

julia> is_offset(ZonedDateTime(dt, tz"Europe/Berlin"))
false

So right now, New York has an offset from its "standard" timezone (and we call that offset daylight savings), but Berlin does not (it transitioned back yesterday)

Related