如何在jq中给定时间戳添加可以以任何时间单位表示的持续时间?

时间:2019-01-23 18:05:59

标签: json jq

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

我正在编写一个jq脚本,该脚本接受一个json,其字段与上述类似。目标是通过添加给定的startTime来增加durationstartTime以毫秒为单位,而duration可以是unit附带的任何时间单位(毫秒,秒,分钟,小时,天,周,月,年)。是否可以执行以下操作?

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

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

1 个答案:

答案 0 :(得分:2)

这是一个考虑leap年的简单解决方案:

# 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 ;

测试

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

产量符合预期(2020年是a年):

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

关键字:addTime