Convert a string date to a timestamp

后端 未结 5 1753
无人及你
无人及你 2021-01-31 22:34

Is there any simple way to convert a RFC HTTP date into a timestamp in Lua?

\"Sat, 29 Oct 1994 19:43:31 GMT\"

into

783467011

5条回答
  •  天命终不由人
    2021-01-31 22:50

    Correcting lhf's example code to account for timezone since os.time() does not have a way to specify the timezone. Also assume all input ends in GMT since this only works with GMT.

    s="Sat, 29 Oct 1994 19:43:31 GMT"
    p="%a+, (%d+) (%a+) (%d+) (%d+):(%d+):(%d+) GMT"
    day,month,year,hour,min,sec=s:match(p)
    MON={Jan=1,Feb=2,Mar=3,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9,Oct=10,Nov=11,Dec=12}
    month=MON[month]
    offset=os.time()-os.time(os.date("!*t"))
    print(os.time({day=day,month=month,year=year,hour=hour,min=min,sec=sec})+offset)
    

    Which gives us 783477811. And we will verify with os.date("!%c") because the ! will make the output in UTC instead of local timezone.

    print(os.date("!%c",783477811))
    --> Sat Oct 29 19:43:31 1994
    

提交回复
热议问题