Convert DateTime format to another DateTime format in Lua

I have a problem when the date value is used to send to the application for some processing, which must first be formatted in a different DateTime format.

What i have

I start with a DateTime value in the format:

  • MM/DD/YYYY hh:mm:ss [AM/PM]

What I need

Somehow with Lua, I need to convert this to a DateTime format:

  • YYYY-MM-DD hh:mm:ss

I was out of luck with the many different things I tried; I will post what I tried, I feel that this may be the most appropriate, but maybe this is not the case either, and there is a simpler or simpler LUA method.

What i tried

print(os.date("%Y-%m-%d %H:%M:%S","05/17/2017 05:17:00 PM"))

Error

stdin: 1: invalid argument # 2 - 'date' (expected number, received string)

What i guess

, , , datetime, , os.date . , datetime, , os.date, , , .

, . , - , , , , .

  • : 05/17/2017 05:17:00 PM

  • 2017-05-17 17:17:00

datetime - .

Lua , , . print() os.date() , , - .

+4
2

, Lua DateTime; Lua , . , Lua, .

, os.date, , Unix time ( 1 1970 .). , Unix-, os.time. , os.time , .

, , , os.date os.time. , @tonypdmtr string.gsub . - , string.match string.format:

local date = '05/17/2017 05:17:00 PM'
local month, day, year, hours, minutes, seconds, amPm = date:match('^(%d%d)/(%d%d)/(%d%d%d%d) (%d%d):(%d%d):(%d%d) ([AP]M)$')
if not month then
    -- Our entire match failed, and no captures were made
    error('could not parse date "' .. date .. '"')
end
if amPm == 'PM' then
    hours = string.format('%2d', tonumber(hours) + 12)
end
local newDate = string.format(
    '%s-%s-%s %s:%s:%s',
    year, month, day, hours, minutes, seconds
)
print(newDate) -- 2017-05-17 17:17:00
+3

: gsub , .

a ='05/17/2017 05:17:00 PM'

b = a:gsub('(%d%d)/(%d%d)/(%d%d%d%d) (%d%d)(:%d%d:%d%d) ([AP]M)',
      function(a,b,c,d,e,am_pm)
        return c .. '-' .. a .. '-' .. b .. ' ' ..
               (am_pm == 'AM' and d or ('%2d'):format(d+12)) .. e
      end)

print(a)
print(b)
+2

Source: https://habr.com/ru/post/1677398/


All Articles