在bash中转换date格式

我有一个这样的格式的date:“2011年6月27日”,我想将其转换为20110627

是否有可能在bash中做?

#since this was yesterday date -dyesterday +%Y%m%d #more precise, and more recommended date -d'27 JUN 2011' +%Y%m%d #assuming this is similar to yesterdays `date` question from you #http://stackoverflow.com/q/6497525/638649 date -d'last-monday' +%Y%m%d #going on @seth's comment you could do this DATE = "27 jun 2011"; date -d"$DATE" +%Y%m%d #or a method to read it from stdin read -p " Get date >> " DATE; printf " AS YYYYMMDD format >> %s" `date -d"$DATE" +%Y%m%d` #which then outputs the following: #Get date >> 27 june 2011 #AS YYYYMMDD format >> 20110627 #if you really want to use awk echo "27 june 2011" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash #note | bash just redirects awk's output to the shell to be executed #FS is field separator, in this case you can use $0 to print the line #But this is useful if you have more than one date on a line 

更多关于date

注意这只适用于GNUdate

我读过:

Solaris版本的date,无法支持-d可以通过replacesunfreeware.com版本的date来解决

 date -d "25 JUN 2011" +%Y%m%d 

输出

 20110625 

只是与bash:

 convert_date () { local months=( JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ) local i for (( i=0; i<11; i++ )); do [[ $2 = ${months[$i]} ]] && break done printf "%4d%02d%02d\n" $3 $(( i+1 )) $1 } 

并像这样调用它

 d=$( convert_date 27 JUN 2011 ) 

或者,如果“旧”datestring存储在一个variables

 d_old="27 JUN 2011" d=$( convert_date $d_old ) # not quoted 

单一的date命令似乎运作良好:

 date -d "27 JUN 2011" +%F 

在OSX上,我使用-f指定input格式,-j不尝试设置任何date和输出格式说明符。 例如:

 $ date -j -f "%m/%d/%y %H:%M:%S %p" "8/22/15 8:15:00 am" +"%m%d%y" 082215 

你的例子:

 $ date -j -f "%d %b %Y" "27 JUN 2011" +%Y%m%d 20110627 

也许自2011年以来发生了一些变化,但这对我有效:

 $ date +"%Y%m%d" 20150330 

不需要-d来获得相同的显示结果。