Lua os.date os.time 分享:
os.date ([format [, time]])
Returns a string or a table containing date and time, formatted according to the given string format
.
If the time
argument is present, this is the time to be formatted (see the os.time
function for a description of this value). Otherwise, date
formats the current time.
If format
starts with '!
', then the date is formatted in Coordinated Universal Time. After this optional character, if format
is the string "*t
", then date
returns a table with the following fields: year
(four digits), month
(1--12), day
(1--31), hour
(0--23), min
(0--59), sec
(0--61), wday
(weekday, Sunday is 1), yday
(day of the year), and isdst
(daylight saving flag, a boolean).
If format
is not "*t
", then date
returns the date as a string, formatted according to the same rules as the C function strftime
.
When called without arguments, date
returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.date()
is equivalent to os.date("%c")
).
看几个输出样例:
local ONE_DAY = 60*60*24
print(os.date())
print(os.date("%m/%d/%y, %H:%M:%S", os.time()))
print(os.date("%m/%d/%y, %H:%M:%S", os.time()-ONE_DAY))
-- 结果分别为:
05/26/14 20:30:42
05/26/14, 20:30:42
05/25/14, 20:30:42
|
os.time ([table])
Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields year
, month
, and day
, and may have fields hour
, min
, sec
, and isdst
(for a description of these fields, see the os.date
function).
The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by time
can be used only as an argument to date
and difftime
.
print(os.time())
print(os.time({day=26, month=5, year=2014}))
print(os.date("%m/%d/%y, %H:%M:%S", os.time({day=26, month=5, year=2014})))
-- 输出结果为
1401108284
1401076800
05/26/14, 12:00:00
|
static int os_time (lua_State *L) {
time_t t;
if (lua_isnoneornil(L, 1)) /* called without args? */
t = time(NULL); /* get current time */
else {
struct tm ts;
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 1); /* make sure table is at the top */
ts.tm_sec = getfield(L, "sec", 0);
ts.tm_min = getfield(L, "min", 0);
ts.tm_hour = getfield(L, "hour", 12);
ts.tm_mday = getfield(L, "day", -1);
ts.tm_mon = getfield(L, "month", -1) - 1;
ts.tm_year = getfield(L, "year", -1) - 1900;
ts.tm_isdst = getboolfield(L, "isdst");
t = mktime(&ts);
}
if (t == (time_t)(-1))
lua_pushnil(L);
else
lua_pushnumber(L, (lua_Number)t);
return 1;
}
|
其实,楼主工作时,是想要返回今天凌晨,也就是00:00:00时的时间值。
local tbl = loadstring(os.date("return {day=%d, month=%m, year=%Y, sec=0, min=0, hour=0}"))()
os.time(tbl)
|