Format date time using jq

277 Views Asked by At

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!

2

There are 2 best solutions below

2
Charles Duffy On BEST ANSWER

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"
13
Shawn On

If you're using a Linux based operating system, the GNU date command can format times and understands timestamps given in ISO-8601 format:

$ date -d "$released_at" +"%A, %B %d, %Y"
Wednesday, September 27, 2023