小编典典

在bash中转换日期格式

linux

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

可以用bash做吗?


阅读 511

收藏
2020-06-02

共1个答案

小编典典

#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

有关日期的更多信息

请注意,这仅适用于GNU日期

我读过:

-d可以通过替换sunfreeware.com版本的日期来解决无法支持的Solaris版本的日期

2020-06-02