Parse Date in Bash



  • 6 Answer(s)

    The GNU coreutils /bin/date binary can be used for many transmutation,

    $ date --date="2009-01-02 03:04:05" "+%d %B of %Y at %H:%M and %S seconds"
    02 January of 2009 at 03:04 and 05 seconds
    

    The date and displays in the parse are given format, if we need we can change that.

    Answered on December 28, 2018.
    Add Comment

    We do not need to change IFS , make changes from dashes and colons into a space .Finally use the read function to read whole program.

    read Y M D h m s <<< ${date//[-:]/ }
    

    Here is an example,

    $ date=$(date +'%Y-%m-%d %H:%M:%S')
    $ read Y M D h m s <<< ${date//[-: ]/ }
    $ echo "Y=$Y, m=$m"
    Y=2009, m=57
    
    Answered on December 28, 2018.
    Add Comment

    Simply, one can use this code.

    $ t='2009-12-03 12:38:15'
    $ a=(`echo $t | sed -e 's/[:-]/ /g'`)
    $ echo ${a[*]}
    2009 12 03 12 38 15
    $ echo ${a[3]}
    12
    
    Answered on December 28, 2018.
    Add Comment
    $ date_in='2017-05-10 13:40:01'
    
    $ format='%Y-%m-%d %H:%M:%S'
    
    $ read -r y m d H M S <<< "$(date -jf "$format" '+%Y %m %d %H %M %S' "$date_in")"
    
    $ for var in y m d H M S; do echo "$var=${!var}"; done
    y=2017
    m=05
    d=10
    H=13
    M=40
    S=01
    Answered on February 28, 2019.
    Add Comment
    $ format='%Y-%m-%d %H:%M:%S%z'
    
    $ TZ=America/Los_Angeles date +"$format" -d 'TZ="UTC" 2017-05-10 02:40:01'
    2017-05-09 19:40:01-0700
    
    $ TZ=UTC date +"$format" -d 'TZ="America/Los_Angeles" 2017-05-09 19:40:01'
    2017-05-10 02:40:01+0000
    Answered on February 28, 2019.
    Add Comment
    date="2009-12-03 15:35:11"
    saveIFS="$IFS"
    IFS="- :"
    date=($date)
    IFS="$saveIFS"
    for field in "${date[@]}"
    do
        echo $field
    done
    
    2009
    12
    03
    15
    35
    11
    Answered on February 28, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.