首页 > 解决方案 > 如何将可以在任何时间单位的持续时间添加到jq中的给定时间戳?

问题描述

{
    "applicationDuration": {
    "duration": 4,
    "unit": "DAY"
    },
    "startTime": {
    "long": 1539196595567
    }
}

我正在编写一个 jq 脚本,它采用与上面类似的字段的 json。目标是startTime通过添加给定的 来增加durationstartTime以毫秒为单位,而duration可以是随unit. 是否可以执行以下操作?

startTime = ToMillis(FOO(startTime) + BAR(duration, unit))

类似于java`s:https ://www.javacodex.com/Date-and-Time/Add-Time-To-A-Timestamp

标签: jsonjq

解决方案


Here's a simple solution that takes into account leap years:

# Input and output are both in milliseconds since the epoch; 
# the output time is later than the input time by $n units, where
# the units are determined by $unit, one of the strings in `dict`.
def later($n; $unit):
  def dict: { YEAR:0, MONTH:1, DAY:2, HOUR:3, MINUTE:4, SECOND:5, MIN:4, SEC:5};
  gmtime
  | .[dict[$unit]] += $n
  | mktime ;

Testing

("2019-01-24" | strptime("%Y-%m-%d") | mktime)
| (later(2; "YEAR"), later(731; "DAY"))
| strftime("%Y-%m-%d")

Output is as expected (as 2020 is a leap year):

"2021-01-24"
"2021-01-24"

keyword: addTime


推荐阅读