Search code examples
stringshelldatedate-formatting

How to get YEAR info from simple date string (YYYYMMDD) with SHELL SCRIPT?


When I run this command to get year info from date '20181102' (format: YYYYMMDD), it works fine:

$ echo $(date --date="20181102" +"%Y")
2018

But when I try with this other date '20181104', I got an error:

$ echo $(date --date="20181104" +"%Y")
date: invalid date ‘20181104’

Is this any bug? Or did I do something wrong?


Solution

  • GNU date utility is a little crude and keeps on misunderstanding the input string. For a good measure, try to always give date dates in @seconds since epoch or in one forms as in man date like "2004-02-29 16:21:42". (Unless you have freebsd date which has -f option.)

    str=20181102
    date --date="$(echo "$str" | cut -c 1-4)-$(echo "$str" | cut -c 5,6)-$(echo "$str" | cut -c 7,8) 00:00:00" +%Y
    

    But really if you know that first 4 characters are year, why don't you just get first 4 characters?

    str=20181102
    echo "$str" | cut -c 1-4
    

    Also note that doing echo $(date ...) is pointless. It's just date .... The echo is not needed in any way.