-2

I have a bunch of JSON with dates in ISO format. How can I print only the year component of the date?

$ echo '{"createdDate": "2005-09-28T16:34:40Z"}' | jq '{ createdYear: ??? }'
{
  "createdYear": "2005"
}
Messa
  • 24,321
  • 6
  • 68
  • 92

2 Answers2

1

Use strptime to convert date string to date object and then strftime to format the date:

$ echo '{"createdDate": "2005-09-28T16:34:40Z"}' |
    jq '
       { createdYear: .createdDate
           | strptime("%Y-%m-%dT%H:%M:%SZ")
           | strftime("%Y") }'
{
  "createdYear": "2005"
}
peak
  • 105,803
  • 17
  • 152
  • 177
Messa
  • 24,321
  • 6
  • 68
  • 92
1

Why not just:

{createdYear: .createdDate[0:4]}
peak
  • 105,803
  • 17
  • 152
  • 177