无法使用 date 命令在 OS X 终端上的 Bash shell 中更改特定日期格式

Lea*_*ner 5 shell bash date quoting

我正在使用该date -d命令将特定日期格式更改为另一种格式。下面是使用的例子

currDate=`Wed 12 Feb 2014`
formattedDate=`date -d"${currDate}" +%Y%m%d`
echo $formattedDate
Run Code Online (Sandbox Code Playgroud)

ter*_*don 9

`除非您将命令的结果分配给变量,否则不应使用反引号 ( ),在这种情况下,您分配的是一个字符串,因此您应该引用它:

currDate="Wed 12 Feb 2014"
formattedDate=`date -d"${currDate}" +%Y%m%d`
echo $formattedDate
Run Code Online (Sandbox Code Playgroud)

我无权访问 mac,所以我无法测试这个,但根据 OSXdate手册页,这应该有效:

formattedDate=`date -jf "%a %d %b %Y" "${currDate}" +%Y%m%d`
Run Code Online (Sandbox Code Playgroud)

OSX 中的许多实用程序都基于相同的 BSD 版本,因此您找到的 Linux 信息并不总是转换为 OSX。从man date上OSX:

 -f      Use input_fmt as the format string to parse the new_date provided
         rather than using the default [[[mm]dd]HH]MM[[cc]yy][.ss] format.

 -j      Do not try to set the date.  This allows you to use the -f flag in 
         addition to the + option to convert one date format to another.
Run Code Online (Sandbox Code Playgroud)


mkc*_*mkc 8

我在我的 OSX 上测试了以下工作:

currDate="Wed 12 Feb 2014"
formattedDate=`date -v"${currDate}" +%Y%m%d`
echo $formattedDate
Run Code Online (Sandbox Code Playgroud)

从联机帮助页-v是:

根据val调整(即取当前日期并显示调整结果;不实际设置日期)秒、分、时、月日、星期、月或年。如果 val 前面有加号或减号,则根据剩余的字符串向前或向后调整日期,否则设置日期的相关部分。可以使用这些标志根据需要多次调整日期。标志按照给定的顺序进行处理。

这将得到正确答案:

date -jf"%a %e %b %Y" "Wed 12 Feb 2014" +%Y%m%d
Run Code Online (Sandbox Code Playgroud)

输出是:

20140212
Run Code Online (Sandbox Code Playgroud)