简体   繁体   中英

How to to extract the year from JSON date using jq

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"
}

Why not just:

{createdYear: .createdDate[0:4]}

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM