简体   繁体   中英

Convert string to date in bash

I have a string in the format "yyyymmdd". It is a string in bash and I want to get it converted into a date so that all other date functions can be used on it.

"20121212" string into "20121212" date with format "%Y%m%d".

This worked for me :

date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'

then you can format output adding parameter '+%Y%m%d'

We can use date -d option

1) Change format to "%Y-%m-%d" format ie 20121212 to 2012-12-12

date -d '20121212' +'%Y-%m-%d'

2)Get next or last day from a given date=20121212. Like get a date 7 days in past with specific format

date -d '20121212 -7 days' +'%Y-%m-%d'

3) If we are getting date in some variable say dat

dat2=$(date -d "$dat -1 days" +'%Y%m%d')

date only work with GNU date (usually comes with Linux)

for OS X, two choices:

  1. change command (verified)

     #!/bin/sh #DATE=20090801204150 #date -jf "%Y%m%d%H%M%S" $DATE "+date \\"%A,%_d %B %Y %H:%M:%S\\"" date "Saturday, 1 August 2009 20:41:50" 

    http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html

  2. Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html

只需使用date命令的-d选项,例如

date -d '20121212' +'%Y %m'

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