Chaining localtime and mktime in jq

206 Views Asked by At

If I do:

$ jq -cn 'now | localtime'
[2022,3,12,21,9,29.65448808670044,2,101]

It correctly gives the "broken down time" representation of current local time.

But If I do:

$ jq -cn 'now | localtime | mktime | localtime'
[2022,3,13,7,10,36,3,102]

It gives back a "broken down time" representation that is different than current local time.

I think when output of localtime is converted to seconds since unix epoch by mktime it is converted wrongly because it wrongly assumes GMT time?

If I do:

$ jq -cn 'now | gmtime | mktime | localtime'

Now this gives correct results (gives "broken down time" representation of current local time).

Am I correct? Thanks.

1

There are 1 best solutions below

0
ikegami On

Yes.

From the jq docs:

The mktime builtin consumes "broken down time" representations of time output by gmtime and strptime.

You originally passed a local time, but it expects a UTC time. As you surmised, this is why your original code failed and the latter code worked. jq's mktime is the inverse of gmtime.[1]

$ jq -rn 'now | ., ( gmtime | mktime )'
1649770973.430903
1649770973

jq does not appear to provide a means to convert from a local time to epoch time.[2]


  1. This differs from the behaviour of C's mktime. C's mktime expects a local time, making it the inverse of localtime.

  2. In C, mktime can serve both roles. While it normally converts from local time, it can also convert from UTC by setting the local time zone to UTC.