Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string date to a timestamp

Tags:

date

lua

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

like image 224
BorisTheBlade Avatar asked Nov 05 '10 10:11

BorisTheBlade


People also ask

Can we convert Date to timestamp?

We can convert date to timestamp using the Timestamp class which is present in the SQL package. The constructor of the time-stamp class requires a long value. So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package).

How do I get a timestamp from a Date?

Getting the Current Time Stamp If you instead want to get the current time stamp, you can create a new Date object and use the getTime() method. const currentDate = new Date(); const timestamp = currentDate. getTime(); In JavaScript, a time stamp is the number of milliseconds that have passed since January 1, 1970.

Can we convert String to timestamp in java?

Use TimeStamp. valueOf() to Convert a String to Timestamp in Java. Use Date. getTime() to Convert a String to Timestamp in Java.


2 Answers

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
like image 85
Arrowmaster Avatar answered Oct 10 '22 15:10

Arrowmaster


use luadate, you can install it with luarocks.

date = require 'date'
local d1 = date('Sat, 29 Oct 1994 19:43:31 GMT')                                                                                               
local seconds = date.diff(d1, date.epoch()):spanseconds()
print(seconds)
like image 21
mescalin Avatar answered Oct 10 '22 14:10

mescalin