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.

 1#!/usr/bin/env lua
 2local luatz = require 'luatz' -- https://github.com/daurnimator/luatz/
 3
 4local tz_name = 'Europe/Berlin'
 5local ts_loc = luatz.time({year=2014, month=12, day=31, hour=23, min=59})
 6
 7-- %z isn't supported yet: https://github.com/daurnimator/luatz/blob/523b2e0f1ece77c569f6db4c040886ed3124512e/luatz/strftime.lua#L178
 8local function tz_off_iso8601(tz_offset_seconds)
 9  local separator = '' -- 8601 %z compliant
10  -- separator = ':' -- 8601 W3C compliant http://www.w3.org/TR/xmlschema-2/#dateTime-timezones
11  local tz_offset_minutes = tz_offset_seconds / 60
12  local sign = string.byte('+')
13  if tz_offset_minutes < 0 then sign = string.byte('-') end
14  return string.format('%c%02d%s%02d', sign, tz_offset_minutes / 60, separator, tz_offset_minutes % 60)
15end
16
17local tzi = assert(luatz.get_tz( tz_name ), 'No such timezone: \''..tz_name..'\'')
18local ts_utc = tzi:utctime ( ts_loc )
19local t_loc = luatz.timetable.new_from_timestamp( ts_loc )
20local t_utc = luatz.timetable.new_from_timestamp( ts_utc )
21
22print( t_loc:strftime('%F %T'), tz_off_iso8601(tzi:find_current( ts_utc ).gmtoff), tz_name )
23print( t_utc:strftime('%F %T'), tz_off_iso8601(0), 'UTC' )