Lua os.time()簡介

os.time()##

  • 原型:os.time ([table])

解釋:按table的內容返回一個時間值(數字),若不帶參數則麼使用當前時間作爲table內容,其中table中可以包含的字段有:year, month, day, hour, min, sec, is

 

首先新建一個文件,將文件命名爲timetest.lua,然後編寫如此如下代碼:dst,其他字段將會被忽略。

local nowtime = os.time();
print("nowtime = "..nowtime)

local exampletime = os.time({year=2008,month=8,day=8,hour=20,min=0,sec=0});
print("exampletime = "..exampletime)

local origintime = os.time({year=1970,month=1,day=1,hour=8,min=0,sec=0});
print("origintime = "..origintime)

-- 錯誤的時間
local errortime = os.time({year=1970,month=1,day=1,hour=0,min=0,sec=0});
print("errortime = "..(errortime or "nil"))

-- 完整日期
local testtime1 = os.time({year=2008,month=1,day=1,hour=8,min=0,sec=0,isdst=false});
print("testtime1 = "..testtime1)

-- 去掉isdst
-local testtime2 = os.time({year=2008,month=1,day=1,hour=8,min=0,sec= 0});-
print("testtime2 = "..testtime2)

-- 去掉sec
local testtime3 = os.time({year=2008,month=1,day=1,hour=8,min=0});
print("testtime3 = "..testtime3)

-- 去掉min
local testtime4 = os.time({year=2015,month=1,day=1,hour=8});
print("testtime4 = "..testtime4)

-- photo紀念日
local testtime5 = os.time({year=2016,month=7,day=17});
print("testtime5 = "..testtime5)

-- 去掉day
local testtime6 = os.time({year=2016,month=7});
print("testtime6 = "..testtime6)
  • 運行結果

 

總結#

  • 這個函數返回一個值意味着它依賴於你的操作系統,在POSIX ,Windows和一些其他的操作系統上,這個數字是記錄了時間原點(1970-01-01)到指點時間的秒數,在個別的系統上結果未定義。
  • 有興趣的朋友可以利用nowtime計算一下我做測試時的確切時間。
  • 由origintime可以看出時間從原點到1970-1-1 08:00:00返回的時間居然是0,其實這是由於時區導致的,北京時間的1970-1-1 08:00:00恰好是0時區時間的1970-1-1 00:00:00,所以返回的時間是0。
  • 明白了origintime相信你就會知道errortime爲什麼會返回nil了,因爲那個時間還沒開始計時呢,理論上應該是負值。
  • 從結果上來看,最後的一次調用造成了程序的出錯,那是因爲table的幾個字段中year, month, day是必填的,而hour, min, sec, isdst是可選的。
  • 還有一點hour, min, sec這幾個值的範圍不一定是正常的時間,甚至可以是負數,比如時間08:62:-10就代表了09:01:50,怎麼樣要不要試試。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章