5

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?

Thelmund
  • 126
  • 1
  • 9
edcoder
  • 503
  • 1
  • 5
  • 19

2 Answers2

4

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.

SolarBear
  • 4,534
  • 4
  • 37
  • 53
2
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'))
tonypdmtr
  • 3,037
  • 2
  • 17
  • 29
  • 2
    Tony, this worked for me as well, but I went with @SolarBear's suggestion (since it displayed first). But thank you so much, I really appreciate it – edcoder Jan 24 '17 at 12:28