bashdateshjqiso8601

Format date time using jq


I have a bash (sh) script that makes several API calls and returns string values. One of them is a 'created_at' attribute of the JSON object returned.

released_at=$(echo -E "${json_response}" | jq -r '.[0].released_at'")

Value returned in ISO 8601 format: "released_at": "2023-09-27T17:36:07.182Z"

I would like it to be displayed as Wednesday, September 27, 2023

What would be the shortest way to achieve that?

Thanks!


Solution

  • jq provides access to your local operating system's strftime and strptime functions. (Note that one needs to be careful about portability when using these: Some libc implementations provide more operators than POSIX guarantees).

    jq '
      .[0].released_at |                # extract field
      split(".")[0] |                  # strip seconds (not portably parsable)
      strptime("%Y-%m-%dT%H:%M:%S") |  # parse with strptime
      strftime("%A, %B, %Y")           # format with strftime
    ' <<'EOF'
    [
      {"released_at": "2023-09-27T17:36:07.182Z"}
    ]
    EOF
    

    ...emits as output:

    "Wednesday, September, 2023"