我尝试在我的bash shell脚本中使用$(date),但是,我想要YYYY-MM-DD格式的日期。 我怎么得到这个?
当前回答
使用最新的Bash(版本≥4.2),您可以使用内置printf格式修饰符%(strftime_format)T:
$ printf '%(%Y-%m-%d)T\n' -1 # Get YYYY-MM-DD (-1 stands for "current time")
2017-11-10
$ printf '%(%F)T\n' -1 # Synonym of the above
2017-11-10
$ printf -v date '%(%F)T' -1 # Capture as var $date
printf比date快得多,因为它是Bash内置的,而date是一个外部命令。
同样,printf -v date…比date=$(printf…)快,因为它不需要派生子shell。
其他回答
如果你想要两个数字格式的年份,比如17而不是2017,请执行以下操作:
DATE=`date +%d-%m-%y`
你可以这样做:
$ date +'%Y-%m-%d'
在bash(>=4.2)中,最好使用printf的内置日期格式化程序(bash的一部分)而不是外部日期(通常是GNU日期)。
是这样的:
# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal
在bash(<4.2)中:
# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly
echo $(date '+%Y-%m-%d')
其他可用的日期格式可以从日期手册页查看(用于外部非bash特定的命令):
man date
使用最新的Bash(版本≥4.2),您可以使用内置printf格式修饰符%(strftime_format)T:
$ printf '%(%Y-%m-%d)T\n' -1 # Get YYYY-MM-DD (-1 stands for "current time")
2017-11-10
$ printf '%(%F)T\n' -1 # Synonym of the above
2017-11-10
$ printf -v date '%(%F)T' -1 # Capture as var $date
printf比date快得多,因为它是Bash内置的,而date是一个外部命令。
同样,printf -v date…比date=$(printf…)快,因为它不需要派生子shell。
#!/bin/bash -e
x='2018-01-18 10:00:00'
a=$(date -d "$x")
b=$(date -d "$a 10 min" "+%Y-%m-%d %H:%M:%S")
c=$(date -d "$b 10 min" "+%Y-%m-%d %H:%M:%S")
#date -d "$a 30 min" "+%Y-%m-%d %H:%M:%S"
echo Entered Date is $x
echo Second Date is $b
echo Third Date is $c
这里x是使用的示例日期&然后示例显示数据格式以及获得日期比当前日期多10分钟。