Skip to content

Commit f871177

Browse files
authored
0.3.1: Handle UTC interpretation correctly
1 parent 153edfe commit f871177

1 file changed

Lines changed: 13 additions & 10 deletions

File tree

src/clock.lua

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
--[[lit-meta
22
name = "Richy-Z/clock"
3-
version = "0.3.0"
3+
version = "0.3.1"
44
dependencies = {}
55
description = "A simple library to get precise UNIX time and other utility functions"
66
tags = { "clock", "time", "unix", "iso8601", "timestamp", "ffi", "milliseconds" }
@@ -93,7 +93,7 @@ local function iso8601(t)
9393
date.year, date.month, date.day, date.hour, date.min, date.sec, millis)
9494
end
9595

96-
--- Parses `str`, hopefully an ISO 8601 formatted timestamp, back into a UNIX timestamp in seconds with fractional milliseconds (if present). Assumes UTC and accounts for local timezones automatically.
96+
--- Parses `str`, hopefully an ISO 8601 formatted timestamp, back into a UNIX timestamp in seconds with fractional milliseconds (if present).
9797
---
9898
--- ```lua
9999
--- local example = "2025-05-27T23:45:12.123Z"
@@ -111,7 +111,7 @@ local function iso8601_parse(str)
111111
"(%d%d%d%d)%-(%d%d)%-(%d%d)T(%d%d):(%d%d):(%d%d)%.(%d+)Z"
112112
)
113113

114-
if not year then -- fallback without milliseconds
114+
if not year then
115115
year, month, day, hour, min, sec = str:match(
116116
"(%d%d%d%d)%-(%d%d)%-(%d%d)T(%d%d):(%d%d):(%d%d)Z"
117117
)
@@ -129,16 +129,19 @@ local function iso8601_parse(str)
129129
hour = tonumber(hour),
130130
min = tonumber(min),
131131
sec = tonumber(sec),
132-
isdst = false, -- avoids daylight saving time offset errors etc
133132
}
134133

135-
-- force UTC interpretation
136-
-- forgetting to implement UTC support was a costly mistake..
137-
local localtime = time(t)
138-
local offset = difftime(time(date("!*t", localtime)), localtime) ---@diagnostic disable-line: param-type-mismatch
139-
local utcTime = localtime + offset
134+
-- interpret as UTC
135+
local local_ts = os.time(t)
136+
local utc_table = os.date("!*t", local_ts)
137+
local local_table = os.date("*t", local_ts)
138+
139+
local offset = os.difftime(
140+
os.time(local_table),
141+
os.time(utc_table)
142+
)
140143

141-
return utcTime + tonumber(millis) / 1000
144+
return local_ts + offset + tonumber(millis) / 1000
142145
end
143146

144147
-- tests

0 commit comments

Comments
 (0)