How to Format a DateTime in Bash (With Examples)


Often you may want to format a datetime in a specific way in Bash.

The easiest way to so do is by using the + command followed by the specific date format:

date +'%Y-%m-%d'

This particular example uses the date command to return the current date and time, then uses the + operator to format the resulting datetime as %Y-%m-%d where:

  • %Y: Returns the year
  • %m: Returns the month
  • %d: Returns the day

Note that you can also use the following syntax to include the hours, minutes and seconds in the datetime:

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

This particular example includes the time component of the current datetime where:

  • %H: Returns the hours
  • %M: Returns the minutes
  • %S: Returns the seconds

The following examples show how to use these methods in practice.

Example 1: Format DateTime Using YYYY-MM-DD

We can use the following syntax to return the current date in Bash using a YYYY-MM-DD format:

date +'%Y-%m-%d'

The following screenshot shows how to use this syntax in practice:

Bash format datetime in YYYY-MM-DD

This returns 2024-07-22, which represents the current date when this article is being written.

Note that you can specify any format that you’d like using the + operator.

For example, you could instead use the following syntax to return the current date using a  MM/DD/YYYY format:

date +'%m/%d%Y'

The following screenshot shows how to use this syntax in practice:

Notice that this returns 07/22/2024, which represents the current date in a MM/DD/YYYY format.

Example 2: Format DateTime Using YYYY-MM-DD HH:MM:SS

We can use the following syntax to return the current date in Bash using a YYYY-MM-DD HH:MM:SS format:

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

The following screenshot shows how to use this syntax in practice:

Bash format datetime with hours minutes seconds

This returns 2024-07-22 10:28:58, which represents the current date and time when this article is being written.

Feel free to use any datetime format that you’d like by using the + operator.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Compare Dates in Bash
How to Calculate Date Difference in Bash
How to Convert Timestamp to Date in Bash

Leave a Reply