我有一个变量,其日期表看起来像这样
* table:
[day]
* number: 15
[year]
* number: 2015
[month]
* number: 2
如何获取当前日期和上述日期之间的天数?非常感谢!
答案 0 :(得分:3)
您可以使用os.time()
将表转换为秒并获取当前时间,然后使用os.difftime()
来计算差异。有关详细信息,请参阅Lua Wiki。
reference = os.time{day=15, year=2015, month=2}
daysfrom = os.difftime(os.time(), reference) / (24 * 60 * 60) -- seconds in a day
wholedays = math.floor(daysfrom)
print(wholedays) -- today it prints "1"
正如@ barnes53指出的那样,可能会在一天内关闭几秒钟,因此它并不理想,但它可能足以满足您的需求。
答案 1 :(得分:1)
您可以使用此处收集的算法:
chrono-Compatible Low-Level Date Algorithms
使用C ++显示算法,但如果您愿意,可以在Lua中轻松实现,或者您可以在C或C ++中实现它们,然后只提供Lua绑定。
使用这些算法的基本思想是计算两个日期的日期数,然后只需减去它们就可以得到天数。
--[[
http://howardhinnant.github.io/date_algorithms.html
Returns number of days since civil 1970-01-01. Negative values indicate
days prior to 1970-01-01.
Preconditions: y-m-d represents a date in the civil (Gregorian) calendar
m is in [1, 12]
d is in [1, last_day_of_month(y, m)]
y is "approximately" in
[numeric_limits<Int>::min()/366, numeric_limits<Int>::max()/366]
Exact range of validity is:
[civil_from_days(numeric_limits<Int>::min()),
civil_from_days(numeric_limits<Int>::max()-719468)]
]]
function days_from_civil(y, m, d)
if m <= 2 then
y = y - 1
m = m + 9
else
m = m - 3
end
local era = math.floor(y/400)
local yoe = y - era * 400 -- [0, 399]
local doy = math.modf((153*m + 2)/5) + d-1 -- [0, 365]
local doe = yoe * 365 + math.modf(yoe/4) - math.modf(yoe/100) + doy -- [0, 146096]
return era * 146097 + doe - 719468
end
local reference_date = {year=2001, month = 1, day = 1}
local date = os.date("*t")
local reference_days = days_from_civil(reference_date.year, reference_date.month, reference_date.day)
local days = days_from_civil(date.year, date.month, date.day)
print(string.format("Today is %d days into the 21st century.",days-reference_days))
答案 2 :(得分:0)
一个样本julian日期函数几乎适用于任何日期AD在下面给出(Lua v5.3因为//但你可以适应早期版本):
local
function div(n,d)
local a, b = 1, 1
if n < 0 then a = -1 end
if d < 0 then b = -1 end
return a * b * (math.abs(n) // math.abs(d))
end
--------------------------------------------------------------------------------
-- Convert a YYMMDD date to Julian since 1/1/1900 (negative answer possible)
--------------------------------------------------------------------------------
function julian(year, month, day)
local temp
if (year < 0) or (month < 1) or (month > 12)
or (day < 1) or (day > 31) then
return
end
temp = div(month - 14, 12)
return (
day - 32075 +
div(1461 * (year + 4800 + temp), 4) +
div(367 * (month - 2 - temp * 12), 12) -
div(3 * div(year + 4900 + temp, 100), 4)
) - 2415021
end