Search code examples
jqstrftime

Jq strftime() to show time in a specific time zone


How to use jq to convert seconds since Unix epoch to a time string in human readable format but adjusted to Sydney, Australia time zone?

I tried filter:

now | strftime("%Y-%m-%dT%H:%M:%SZ")

But I don't know how to adjust the time format string to convey Sydney, Australia time zone.

Possibly I need to replace "Z" with the relevant time zone?


Solution

  • Both of the following convert to the time zone indicated by the TZ environment variable var:

    localtime | strftime(...)
    
    strflocaltime(...)
    

    For example,

    $ jq -nr 'now | strftime("%FT%T")'
    2022-02-14T06:14:07
    
    $ jq -nr 'now | gmtime | strftime("%FT%T")'
    2022-02-14T06:14:07
    
    $ jq -nr 'now | localtime | strftime("%FT%T")'
    2022-02-14T02:14:07
    
    $ jq -nr 'now | strflocaltime("%FT%T")'
    2022-02-14T02:14:07
    

    That uses your local time, as determined by TZ environment variable. Adjust as needed.

    $ TZ=America/Halifax jq -nr 'now | strflocaltime("%FT%T")'
    2022-02-14T02:14:07
    
    $ TZ=America/Toronto jq -nr 'now | strflocaltime("%FT%T")'
    2022-02-14T01:14:07
    
    $ TZ=America/Vancouver jq -nr 'now | strflocaltime("%FT%T")'
    2022-02-14T22:14:07
    

    If you want to convert to different time zones in a single run of jq, you're out of luck. jq doesn't support converting to/from time zones other than UTC and this time zone.

    Tested with both 1.5 and 1.6.