YYYY-MM-DD format date in shell script

Viewed 1773259

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

17 Answers
$(date +%F)

output

2018-06-20

Or if you also want time:

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

can be used to remove colons (:) in between

output

2018-06-20_09-55-58

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

printf is much faster than date since it's a Bash builtin while date is an external command.

As well, printf -v date ... is faster than date=$(printf ...) since it doesn't require forking a subshell.

I use the following formulation:

TODAY=`date -I`
echo $TODAY

Checkout the man page for date, there is a number of other useful options:

man date

I use $(date +"%Y-%m-%d") or $(date +"%Y-%m-%d %T") with time and hours.

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

$ man strftime

to remind myself of all the possibilities for time formatting options.

Try to use this command :

date | cut -d " " -f2-4 | tr " " "-" 

The output would be like: 21-Feb-2021

#!/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

Here x is sample date used & then example displays both formatting of data as well as getting dates 10 mins more then current date.

I used below method. Thanks for all methods/answers

ubuntu@apj:/tmp$ datevar=$(date +'%Y-%m-%d : %H-%M')
ubuntu@apj:/tmp$ echo $datevar
2022-03-31 : 10-48

You can set date as environment variable and later u can use it

setenv DATE `date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"

or

DATE =`date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"

Try this code for a simple human readable timestamp:

dt=$(date)
echo $dt

Output:

Tue May 3 08:48:47 IST 2022
echo "`date "+%F"`"

Will print YYYY-MM-DD

Related