How to Convert String to Date in Bash (With Example)


You can use the following syntax in Bash to convert a string to a date:

date -d '10/15/2024'

This particular example converts the string ’10/15/2024′ to a date.

Note: We use the -d operator to specify that we would like to display the date described by the string that follows it. Without this operator, the date command would simply return the current date and time.

The following example shows how to use this syntax in practice.

Example: How to Convert String to Date in Bash

Suppose we would like to convert the string “10/15/2024” to a date.

We can use the following syntax to do so:

date -d '10/15/2024'

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

Bash convert string to date

We can see that the string ’10/15/2024′ has been converted to a date represented as:

  • Tue Oct 15 00:00:00 EDT 2024

It’s worth noting that the date command can also handle dates in a variety of formats.

For example, suppose that we would like to convert the string ‘Oct 15 2024’ to a date.

We can use the following syntax to do so:

date -d 'Oct 15 2024'

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

We can see that the string ‘Oct 15 2024’ has been converted to a date.

Also note that we can use the + operator to format the date in any way that we would like.

For example, we can use the following syntax to convert the string ‘Oct 15 2024’ to a date and then format it to be shown as mm/dd/yyyy:

date -d 'Oct 15 2024' +'%m/%d/%Y'

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

Bash convert string to date with specific format

Notice that we’ve successfully converted the string ‘Oct 15 2024’ to a date and then formatted it to be shown as 10/15/2024.

Note: Feel free to use whatever format you would like within the + operator.

Related Tutorials

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

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

Leave a Reply