gpt4 book ai didi

loops - Lua 日期操作循环

转载 作者:行者123 更新时间:2023-12-04 20:44:47 24 4
gpt4 key购买 nike

我正在尝试运行带有两个我想调整的日期值的批处理脚本,然后再次运行该脚本。我想引用一个 lua 脚本,它将为我调整这些日期值。我使用 lua 只是因为大部分项目都是用这种语言编码的。

如果我的变量是 start=01/01/2012 和 end=02/01/2012,我该如何将这两个日期向前移动 14 天?然后我想让它运行,然后再次循环并向前移动 14 天。这将继续,直到循环中断,我决定的日期。是否有可能以这种方式实现这一目标,或者我是否在接近这个错误?

我想我可以用一个函数来做一些涉及 string.gsub 的事情,该函数可以从我的日期中提取“dd”并将其向上移动 14。但是,是否可以进行这种日期算术,或者在我到达时会立即中断月底,它会尝试读取像 01/45/2012 这样的日期?

最佳答案

您的规范不完全清楚。我想以下脚本可能会有所帮助。
诀窍是将日期转换为时间值,如 os.time 返回的那样,可以作为简单的数字进行比较。

为此,您首先必须解析日期的字符串形式,然后将它们转换为适合提供给 os.time 的表格形式。 .请注意,增加这些表的字段(表示其组件拆分的日期)已经处理了时间算术,即指定 day例如,值为 32 的字段转换为时间值时将正确换行到下个月。

当您到达目标日期时,您可以使用 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

关于loops - Lua 日期操作循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19776082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com