erol yeniaras
erol yeniaras

Reputation: 3795

How to add a duration which can be in any time unit to a given timestamp in jq?

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

I am writing a jq script which takes a json with the fields similar to above. The goal is to increment the startTime by adding the given duration. startTime is in milliseconds whereas duration can be any time unit (ms, sec, min, hr, day, week, month, year) which is provided with unit. Is it possible to do something like below?

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

Similar to java`s: https://www.javacodex.com/Date-and-Time/Add-Time-To-A-Timestamp

Upvotes: 1

Views: 353

Answers (1)

peak
peak

Reputation: 116880

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

Upvotes: 3

Related Questions