Search code examples
datetimeluatimestampdatetime-conversion

Lua - Convert XML datetime into UTC timestamp


I do not have much experience with lua and could not accomplish a simple (I think) task:

Given a String that contains a timestamp (parsed from an XML file), how could I convert it into TIMESTAMP in UTC format using a lua script?

my_date = "2019-11-21T22:35:03.332+02:00"

Basically I'd like to write a function/script that when passing such a String, I'd get back an empty string (if not possible to convert) or a timestamp in UTC format (YYYY-MM-DD HH:MS:SS)

In my_date the final part ...+02:00 means the (local) time is 2 hours ahead of UTC.

my_utc_date = "2019-11-21 20:35:03"


Solution

  • There are several ways to achive your goal. Here I show you how to use string.match and string patterns to get the string elements. The rest is simple maths.

    -- our input
    local my_date = "2019-11-21T22:35:03.332+02:00"
    -- we can just keep anything befor T as our date
    local day = my_date:match("(.*)T")
    -- now parse the UTC offset
    local offsetH, offsetM = my_date:match("([%+%-]%d%d):(%d%d)")
    
    -- apply sign to our minute offset
    offsetM = offsetM * (tonumber(offsetH) > 0 and 1 or -1)
    
    -- get time components
    local h, m, s, ms = my_date:match("(%d%d):(%d%d):(%d%d).(%d%d%d)")
    
    -- fix our and minute to get UTC
    h = h - offsetH
    m = m - offsetM
    -- round seconds as we have microseconds in our input
    s = math.floor(s + ms / 1000 + .5)
    
    -- now put everything together with leading zeros
    local my_utc_date = string.format("%s %02d:%02d:%02d", day, h, m, s)
    
    print(my_utc_date)