Linux - Convert string to date using date command

By xngo on February 27, 2019

# Convert current date to different format.
    date_string=$(date +"%Y-%m-%d.%0k.%M.%S")
 
# Convert string to date
    date -d '20120131'          +'%Y-%m-%d'
    date -d '20120131 - 7 days' +'%Y-%m-%d' # 7 days before 2012-01-31
 
    date -d '20120131 7 days'
    date -d '28-DEC-2012 7 days'
    date -d '2012-01-31 7 days'
    date -d '2012-01-31 4:10:10PM 7 days'
    date -d '2012-01-31 16:10:55 7 days'
 
    # Get 2 months ago date string
    date --date='2 months ago' +%Y-%m-%d
 
# Get total elapsed time.   
    # Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC).
        T="$(date +%s)"
 
    # Do some work.
        sleep 3s
 
    # Get total elapsed time.
        T="$(($(date +%s)-T))"
        printf "Elapsed time: %02d:%02d:%02d:%02d [DD:HH:MM:SS]\n" \
                "$((T/86400))" "$((T/3600%24))" "$((T/60%60))" "$((T%60))"

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.