Lua os.date os.time 分享:
不知道大家在工作中有没有常常用到这两个库函数。
比如:界面中需要显示日期相关的文本,或者用到时间相关的判断。那这两个函数会帮上大忙。
os.date():
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")
).
看几个输出样例:
|
Format格式注解:
如果 os.date() 的格式字符是 "*t", 则会返回一个table,其域包含 year,month,day,hour,min,sec,wday,yday,isdst。(见英文部分)
一开始不太明白返回这个 Table 来作何用,今天在使用 os.time() 时,就明白了。
os.time():
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
.
如果没有任何参数,就会返回当前时间;
如果参数一个table,并且table的域必须有 year, month, day, 可有也可以没有 hour, min, sec, isdst,则会返回table所代表日期的时间。
返回值是一个 number ,其值取决于你的系统。返回值通常被用于 os.date 和 os.difftime。
看几个输出样例:
|
上面说到,os.time() 的参数可以是一个 table,如果不指定 sec,hour,min这三个域,其默认值会是当天中午 12:00:00 的时间。当然如果大家去看源码就知道了。
os.time 源码:
|
其实,楼主工作时,是想要返回今天凌晨,也就是00:00:00时的时间值。
我的做法是:
|
注意的就是一定要指定 sec,min,hour 这三个值,否则默认是12:00:00