is there any way to parse a date in jq which contains milliseconds, or is there a way to get the interval between two dates without parsing?

Viewed 49

So basically i need to get an interval between 2 dates and i have found how to do that using mktime, then deducting the two numbers.

But from my searching in the strptime c library, there doesnt seem to be a way to parse a date containing milliseconds, so im asking if there is any way around this, or if there is any way to parse a date containing milliseconds.

Edit: if there is any way to round up or down the date, or just remove the milliseconds that would work too

example:

{
 "ActiveFrom": "2022-02-13T11:32:01.321345+04:00",
 "ActiveTo": "2022-02-13T11:33:13.031743+04:00"
}
2 Answers

You could strip the fractional seconds with a substitution, and then go via strptime (required because of non-UTC timezone) to get a Unix timestamp:

echo '{
 "ActiveFrom": "2022-02-13T11:32:01.321345+04:00",
 "ActiveTo": "2022-02-13T11:33:13.031743+04:00"
}' \
  | jq '.ActiveFrom
      | sub("\\.[[:digit:]]+"; "")
      | strptime("%Y-%m-%dT%H:%M:%S%z")
      | mktime'

resulting in 1644751921 (jq playground).

If your dates are of OBJECT data type, you can easily calculate the interval like this:

var interval = date_later - date_early;
Related