Advertisement
Advertisement


YYYY-MM-DD format date in shell script


Question

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

2020/04/16
1
1137
4/16/2020 8:11:07 AM

Accepted Answer

In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date (usually GNU date).

As such:

# 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

In 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')

Other available date formats can be viewed from the date man pages (for external non-bash specific command):

man date
2019/07/12
1863
7/12/2019 11:53:20 AM

Try: $(date +%F)

2009/09/09

You can do something like this:

$ date +'%Y-%m-%d'
2013/10/14

You're looking for ISO 8601 standard date format, so if you have GNU date (or any date command more modern than 1988) just do: $(date -I)

2014/05/03

$(date +%F_%H-%M-%S)

can be used to remove colons (:) in between

output

2018-06-20_09-55-58
2018/06/20

date -d '1 hour ago' '+%Y-%m-%d'

The output would be 2015-06-14.

2016/06/14

Source: https://stackoverflow.com/questions/1401482
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]