Date formatting in Lua

I get the date from the database in the following format:

vardate =  '01/20/2017 09:20:35' - mm/dd/yyyy hh:mm:ss

I want to convert it to dd-mm-yyyy hh: mm: ss format

Can I get some recommendations on how I can get the format I want?

+4
source share
2 answers

Date formatting in Lua is quite simplified. If you only need to convert it from one format to another, and this format does not change, you can simply use string.match:

function convertDate(vardate)
    local d,m,y,h,i,s = string.match(vardate, '(%d+)/(%d+)/(%d+) (%d+):(%d+):(%d+)')
    return string.format('%s/%s/%s %s:%s:%s', y,m,d,h,i,s)
end

-- Call it this way
convertDate('01/20/2017 09:20:35')

If you need something more active, I suggest using an external library.

+3
source
function ConvertDate(date)
  return (date:gsub('(%d+)/(%d+)/(%d+) (%d+:%d+:%d+)','%2-%1-%3 %4'))
end

-- test
print(ConvertDate('01/20/2017 09:20:35'))
+1
source

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


All Articles