Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date formatting in Lua

Tags:

date

lua

I am retrieving a date from a database in the following format:

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

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

Can I get some guidance on how I could get the format I want?

like image 664
edcoder Avatar asked Jan 23 '17 16:01

edcoder


2 Answers

Date formatting in Lua is pretty simplistic. If you only need to convert it from one format to another, and that format does not change, you could 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 involved, I suggest using an external library.

like image 112
SolarBear Avatar answered Sep 30 '22 13:09

SolarBear


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'))
like image 42
tonypdmtr Avatar answered Sep 30 '22 15:09

tonypdmtr