YYYY-MM-DD format date in shell script

2019-01-03 18:50发布

I tried using $(date) in my bash shell script, however I want the date in YYYY-MM-DD format. How do I get this?

11条回答
Melony?
2楼-- · 2019-01-03 19:31

With recent Bash (version ≥ 4.2), you can use the builtin printf with the format modifier %(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
查看更多
做自己的国王
3楼-- · 2019-01-03 19:32

In Bash:

get year-month-day from date

DATE=`date +%Y-%m-%d`

get year-month-day hour:minute:second from date

DATE=`date '+%Y-%m-%d %H:%M:%S'`

Other available date formats can be viewed from the date man pages:

man date
查看更多
别忘想泡老子
4楼-- · 2019-01-03 19:34
date -d '1 hour ago' '+%Y-%m-%d'

The output would be 2015-06-14.

查看更多
We Are One
5楼-- · 2019-01-03 19:36

if you want the year in a two number format such as 17 rather than 2017, do the following:

DATE=`date +%d-%m-%y`
查看更多
We Are One
6楼-- · 2019-01-03 19:36

Whenever I have a task like this I end up falling back to

$ man strftime

to remind myself of all the possibilities.

查看更多
Luminary・发光体
7楼-- · 2019-01-03 19:44

Try: $(date +%F)

查看更多
登录 后发表回答