2010-11-05 101 views

回答

8

下面的代碼做到這一點,除了它不處理時區:

s="Sat, 29 Oct 1994 19:43:31 GMT" 
p="%a+, (%d+) (%a+) (%d+) (%d+):(%d+):(%d+) (%a+)" 
day,month,year,hour,min,sec,tz=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] 
print(os.time({tz=tz,day=day,month=month,year=year,hour=hour,min=min,sec=sec})) 

但它打印下面783467011.代碼告訴我們, 1288374211是不同日期:

print(os.date("%c",1288374211)) 
--> Fri Oct 29 15:43:31 2010 
print(os.date("%c",783467011)) 
--> Sat Oct 29 19:43:31 1994 
+3

有關日期+時間庫,請參閱http://luaforge.net/projects/date/。 – lhf 2010-11-05 11:14:12

14

更正lhf的示例代碼來解釋時區,因爲os.time()沒有指定時區的方法。同時假設所有輸入都以GMT結束,因爲這隻能與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) 

哪給了我們783477811.我們將用os.date(「!%c」)進行驗證,因爲!將以UTC而不是本地時區輸出。

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

!很好,thx。 – Tim 2016-03-04 08:26:35

8

如果您需要將值轉換爲UNIX時間戳,代碼這樣做會是這樣的:

-- Assuming a date pattern like: yyyy-mm-dd hh:mm:ss 
local pattern = "(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)" 
local timeToConvert = "2011-01-01 01:30:33" 
local runyear, runmonth, runday, runhour, runminute, runseconds = timeToConvert:match(pattern) 

local convertedTimestamp = os.time({year = runyear, month = runmonth, day = runday, hour = runhour, min = runminute, sec = runseconds}) 
+0

查看我的答案和額外的時區處理它。只有在當前時區(和夏令時)與其運行的系統一致時,您的答案纔有效。 – Arrowmaster 2011-05-05 22:47:58

4

使用luadate,你可以用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) 
相關問題