Lua日期操作循环。

我想运行一个批处理脚本,其中包含两个日期值,我想要调整这些值,然后再次运行脚本。我想要引用一个 lua 脚本,让它为我调整这些日期值。我使用 lua 是因为项目的大部分代码都是用这种语言编写的。

如果我的变量是 start=01/01/2012 和 end=02/01/2012,我该如何将这两个日期都往前推进 14 天?然后我想让它运行,然后循环再次运行,并将两个日期再向前推进另外 14 天。这将继续进行,直到循环跳出,以我决定的日期为止。我能否用这种方式完成这项任务,还是我在处理上出了错?

我想我可以使用 string.gsub 来进行某些操作,并使用一个函数从我的日期中提取 "dd" 并将其向前调整 14 天。不过,这种日期算术计算是否可行,或者一旦到达月末,就会出现问题,它会尝试读取像 01/45/2012 这样的日期?

点赞
用户258523
用户258523

你可能需要使用string.match进行解析,并使用os.timeos.date来构建正确的新时间字符串(os.time用于将新添加的日期转换为正确的月份/年份,os.date用于将os.time返回的时间转换为易于理解的字符串/表格),以执行日期检查循环/停止。

2013-11-04 20:16:44
用户2633423
用户2633423

您的规范不太清楚。我猜以下脚本可能会有所帮助。 技巧是将您的日期转换为由os.time返回的时间值,这些值可以像简单数字一样比较。

为此,您首先必须解析date的字符串形式,然后将其转换为适合输入os.time的表格形式。请注意,增加这些表格的字段(表示具有其组件分裂的日期)已处理时间算术,即将具有例如32的值的day'字段传递给os.time时,将正确包装为下一个月。

当您到达目标日期时,使用os.date将时间值转换回所需的日期格式。

local TARGET_DATE = "03/05/2012"

-- get the two dates from the command line of this lua script

local date1 = arg[1]
local date2 = arg[2]

date1 = "01/01/2012"    -- test data - remove in actual script
date2 = "02/01/2012"    -- test data - remove in actual script

-- parse the dates (assuming the format day/month/year)

local d1, m1, y1 = string.match( date1,  '^(%d%d)/(%d%d)/(%d%d%d%d)$' )
local d2, m2, y2 = string.match( date2,  '^(%d%d)/(%d%d)/(%d%d%d%d)$' )
local td, tm, ty = string.match( TARGET_DATE,  '^(%d%d)/(%d%d)/(%d%d%d%d)$' )

print( d1, m1, y1 ) -- debug
print( d2, m2, y2 ) -- debug
print( td, tm, ty ) -- debug

date1_tbl = { day = d1, month = m1, year = y1 }
date2_tbl = { day = d2, month = m2, year = y2 }

local time1 = os.time( date1_tbl )
local time2 = os.time( date2_tbl )
local target_time = os.time { day = td, month = tm, year = ty }

-- loop until both dates exceed target date
while time1 < target_time or time2 < target_time  do
    date1_tbl.day = date1_tbl.day + 14
    date2_tbl.day = date2_tbl.day + 14
    time1 = os.time( date1_tbl )
    time2 = os.time( date2_tbl )
end

-- rebuild new dates
local newdate1 = os.date( "%d/%m/%Y", time1 )
local newdate2 = os.date( "%d/%m/%Y", time2 )

print( newdate1 ) -- debug
print( newdate2 ) -- debug
2013-11-04 20:26:59