bash how to format date


The easiest way to get a date in YYYY-MM-DD is follows:

date -I

Output: 2016-06-07

The parameter ā€œIā€ tells the date command, the ISO date format is required.

Of course, you can also use your own definition. %Y means year, %m means month, and %d means day:

date +%Y-%m-%d

Output: 2016-06-07, the same.

If you want to display also hours:minutes:second, let's do:

date +%Y-%m-%d:%H:%M:%S

Output: 2016-06-07:17:02:19

You fill the variable date as follows:

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

Here are some examples of format control:

  • %u - day of week(1..7), 1 is Monday
  • %w - day of week(0..6), 0 is Sunday
  • %U - week number of year, with Sunday as the first day of the week (00..53)
  • %V - week number of year, with Monday as the first day of the week (00..53)
  • %s - seconds since 1.1.1970 UTC
  • %Y - year
  • %y - last two digits of year(00..99)
  • %r - locale's 12-hour clock time
  • %R - 24-hour hour and minute