From 10b0b596ae80e414d41417f67d37932882d6af58 Mon Sep 17 00:00:00 2001 From: Mars Peng Date: Tue, 28 Nov 2023 22:13:49 +0800 Subject: [PATCH] Feat: Support ISO 8601 timestamp with offset (#124) Fixes timezone offset support to date parsing from Gitlab as specified by the ISO 8601 format --- lua/gitlab/spec/util_spec.lua | 4 ++++ lua/gitlab/utils/init.lua | 15 ++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lua/gitlab/spec/util_spec.lua b/lua/gitlab/spec/util_spec.lua index 079eff6..629a2b8 100644 --- a/lua/gitlab/spec/util_spec.lua +++ b/lua/gitlab/spec/util_spec.lua @@ -205,6 +205,10 @@ describe("utils/init.lua", function() { "2016-11-22T1:25:09.482Z", "-0500", "11/21/2016 at 20:25" }, { "2016-11-22T1:25:09.482Z", "-0000", "11/22/2016 at 01:25" }, { "2017-3-22T13:25:09.482Z", "+0700", "03/22/2017 at 20:25" }, + { "2023-10-28T11:25:09.482-05:00", "-0500", "10/28/2023 at 11:25" }, + { "2016-11-21T20:25:09.482-05:00", "-0500", "11/21/2016 at 20:25" }, + { "2016-11-22T1:25:09.482-00:00", "-0000", "11/22/2016 at 01:25" }, + { "2017-3-22T20:25:09.482+07:00", "+0700", "03/22/2017 at 20:25" }, } for _, val in ipairs(tests) do local got = u.format_to_local(val[1], val[2]) diff --git a/lua/gitlab/utils/init.lua b/lua/gitlab/utils/init.lua index cb29a41..98552a0 100644 --- a/lua/gitlab/utils/init.lua +++ b/lua/gitlab/utils/init.lua @@ -168,7 +168,18 @@ end ---@param offset string The offset of the user's local time zone, e.g. -0500 for EST ---@return string M.format_to_local = function(date_string, offset) + -- ISO 8601 format + -- 2021-01-01T00:00:00.000Z local year, month, day, hour, min, sec, _, tzOffset = date_string:match("(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+).(%d+)Z") + if year == nil then + -- ISO 8601 format with timezone offset + -- 2021-01-01T00:00:00.000-05:00 + local tzOffsetSign, tzOffsetHour, tzOffsetMin + year, month, day, hour, min, sec, _, tzOffsetSign, tzOffsetHour, tzOffsetMin = + date_string:match("(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+).(%d+)([%+%-])(%d%d):(%d%d)") + tzOffset = tzOffsetSign .. tzOffsetHour .. tzOffsetMin + end + local localTime = os.time({ year = year, month = month, @@ -179,7 +190,9 @@ M.format_to_local = function(date_string, offset) tzOffset = tzOffset, }) - local localTimestamp = localTime + M.offset_to_seconds(offset) + -- Subtract the tzOffset from the local time to get the UTC time + local localTimestamp = tzOffset ~= nil and localTime - M.offset_to_seconds(tzOffset) or localTime + localTimestamp = localTimestamp + M.offset_to_seconds(offset) return tostring(os.date("%m/%d/%Y at %H:%M", localTimestamp)) end