時區 |
|
+hhmm
或 -hhmm
。無法使用 os.date("%z")
,因為其傳回值的格式無法攜帶,特別是 Windows 系統未對 strftime()
使用 C99 語意。以下程式碼應可攜地產生目前區域時間的時區字串。
注意:以下只計算「現在」的時區偏移值,這與 os.date("%z")
不同,后者可處理過去或未來的時間,並考量日光節約時間。或者,您可以使用下方所述的 get_timezone_anystamp(ts)
-- Compute the difference in seconds between local time and UTC. local function get_timezone() local now = os.time() return os.difftime(now, os.time(os.date("!*t", now))) end timezone = get_timezone() -- Return a timezone string in ISO 8601:2000 standard form (+hhmm or -hhmm) local function get_tzoffset(timezone) local h, m = math.modf(timezone / 3600) return string.format("%+.4d", 100 * h + 60 * m) end tzoffset = get_tzoffset(timezone) --[[ debugging for _, tz in ipairs(arg) do if tz == '-' then tz = timezone else tz = 0 + tz end print(tz, get_tzoffset(tz)) end --]] -- return the timezone offset in seconds, as it was on the time given by ts -- Eric Feliksik local function get_timezone_offset(ts) local utcdate = os.date("!*t", ts) local localdate = os.date("*t", ts) localdate.isdst = false -- this is the trick return os.difftime(os.time(localdate), os.time(utcdate)) end