我尝试在我的bash shell脚本中使用$(date),但是,我想要YYYY-MM-DD格式的日期。 我怎么得到这个?
当前回答
$(date +%F)
输出
2018-06-20
或者如果你也需要时间:
$(date +%F_%H-%M-%S)
可以用来删除冒号(:)之间
输出
2018-06-20_09-55-58
其他回答
我使用下面的方法。谢谢所有的方法/回答
ubuntu@apj:/tmp$ datevar=$(date +'%Y-%m-%d : %H-%M')
ubuntu@apj:/tmp$ echo $datevar
2022-03-31 : 10-48
在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
你可以这样做:
$ date +'%Y-%m-%d'
每当我有这样的任务时,我就会回到
$ man strftime
提醒自己所有的时间格式选项的可能性。
date -d '1 hour ago' '+%Y-%m-%d'
输出将是2015-06-14。