In this tutorial, we will learn the available format options for date command and how to format a date in Bash Scripting, with examples.

Bash Date

To format Bash Date to a required one, bash shell provides date command along with many format options.

Bash Date Command

Following is the syntax of date command

$ date
ADVERTISEMENT

Format Bash Date with Options

As already said, you can format the Bash Date. And the format you wish may contain spaces as well.

Date command accepts options if provided any

$ date +<format-option><format-option>

To format date with spaces, use the syntax

$ date '+<format-option><format-option> <format-option>'

List of Bash Date Formatting Options

Following are the list of available options for date command :

Format optionPart of DateDescriptionExample Output
date +%aWeekdayName of weekday in short (like Sun, Mon, Tue, Wed, Thu, Fri, Sat)Mon
date +%AWeekdayName of weekday in full (like Sunday, Monday, Tuesday)Monday
date +%bMonthName of Month in short (like Jan, Feb, Mar )Jan
date +%BMonthMonth name in full (like January, February)January
date +%dDayDay of month (e.g., 01)04
date +%DMM/DD/YYCurrent Date; shown in MM/DD/YY02/18/18
date +%FYYYY-MM-DDDate; shown in YYYY-MM-DD2018-01-19
date +%HHourHour in 24-hour clock format18
date +%IHourHour in 12-hour clock format10
date +%jDayDay of year (001..366)152
date +%mMonthNumber of month (01..12) (01 is January)05
date +%MMinutesMinutes (00..59)52
date +%SSecondsSeconds (00..59)18
date +%NNanosecondsNanoseconds (000000000..999999999)300231695
date +%THH:MM:SSTime as HH:MM:SS (Hours in 24 Format)18:55:42
date +%uDay of WeekDay of week (1..7); 1 is Monday7
date +%UWeekDisplays week number of year, with Sunday as first day of week (00..53)23
date +%YYearDisplays full year i.e. YYYY2018
date +%Z TimezoneTime zone abbreviation (Ex: IST, GMT)IST

You may use any of the above-mentioned format options (first column) for the date command in the aforementioned syntax.

Examples

Bash Date Format MM-DD-YYYY

To format date in MM-DD-YYYY format, use the command  date +%m-%d-%Y.

Bash Script

#!/bin/bash

d=`date +%m-%d-%Y`
echo $d    # 12-30-2017

Output

11-20-2020

Please observe the upper and lower case letters : %m for month, %d for day and %Y for year. %M would mean minutes.

Bash Date Format MM-YYYY

To format date in MM-YYYY format, use the command  date +%m-%Y .

Bash Script

#!/bin/bash

d=`date +%m-%Y`

echo $d    # 12-2017

Output

11-20-2020

Bash Date Format: Weekday DD-Month, YYYY

To format date in MM-DD-YYYY format, use the command date +%m-%d-%Y.

Bash Script

#!/bin/bash

d=`date '+%A %d-%B, %Y'`

echo $d   #  Saturday 30-December, 2017

Output

11-20-2020

Conclusion

Concluding this Bash TutorialBash Date, we have learned to use date command, the list of Bash Date Format options available with the date command and some of the examples demonstrating the usage of the format options.