lua & timezones by name

Mon, 20. Apr 2015

Categories: en development Tags: ISO8601 lua TimeZone W3C

A bit hard to puzzle due to scarce documentation.

#!/usr/bin/env lua
local luatz = require 'luatz' -- https://github.com/daurnimator/luatz/

local tz_name = 'Europe/Berlin'
local ts_loc = luatz.time({year=2014, month=12, day=31, hour=23, min=59})

-- %z isn't supported yet: https://github.com/daurnimator/luatz/blob/523b2e0f1ece77c569f6db4c040886ed3124512e/luatz/strftime.lua#L178
local function tz_off_iso8601(tz_offset_seconds)
  local separator = '' -- 8601 %z compliant
  -- separator = ':' -- 8601 W3C compliant http://www.w3.org/TR/xmlschema-2/#dateTime-timezones
  local tz_offset_minutes = tz_offset_seconds / 60
  local sign = string.byte('+')
  if tz_offset_minutes < 0 then sign = string.byte('-') end
  return string.format('%c%02d%s%02d', sign, tz_offset_minutes / 60, separator, tz_offset_minutes % 60)
end

local tzi = assert(luatz.get_tz( tz_name ), 'No such timezone: \''..tz_name..'\'')
local ts_utc = tzi:utctime ( ts_loc )
local t_loc = luatz.timetable.new_from_timestamp( ts_loc )
local t_utc = luatz.timetable.new_from_timestamp( ts_utc )

print( t_loc:strftime('%F %T'), tz_off_iso8601(tzi:find_current( ts_utc ).gmtoff), tz_name )
print( t_utc:strftime('%F %T'), tz_off_iso8601(0), 'UTC' )