How to Calculate Date Difference in Bash (With Example)


Often you may want to calculate the difference between two dates in Bash.

You can use the following methods to do so:

Method 1: Calculate Difference Between Two Dates

echo $((($(date -d "$date2" +%s) - $(date -d "$date1" +%s))/86400))

This particular example calculates the number of days between the date stored in the $date1 variable and the date stored in the $date2 variable.

Method 2: Calculate Difference Between Specific Date and Today

echo $((($(date -d "$my_date" +%s) - $(date -d "$(date +%F)" +%s))/86400))

This particular example calculates the number of days between the date stored in the $my_date variable and today’s date.

Note: We use $(date +%F) to get today’s date in Bash.

The following examples show how to use each method in practice.

Example 1: Calculate Difference Between Two Dates in Bash

Suppose that we create the following date variables in Bash:

  • $date1: 2024-01-25
  • $date2: 2024-04-13

We can use the following syntax to calculate the difference between the two dates:

date1=2024-01-25
date2=2024-04-13

echo $((($(date -d "$date2" +%s) - $(date -d "$date1" +%s))/86400))

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

Bash calculate date difference

From the output we can see that there are 78 days between January 25, 2024 and April 13, 2024.

Note: We divide by 86,400 because this is the number of seconds in a day. If we didn’t divide by this number then the date difference would be displayed in seconds instead of days.

Example 2: Calculate Difference Between Specific Date and Today in Bash

Suppose that we would like to calculate the number of days between the following two dates in Bash:

  • $my_date: 2024-10-30
  • Today’s date: 2024-04-15

We can use the following syntax to calculate the difference between the two dates:

my_date=2024-10-30

echo $((($(date -d "$my_date" +%s) - $(date -d "$(date +%F)" +%s))/86400))

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

Bash calculate date difference between specific date and today

From the output we can see that there are 198 days between October 30, 2024 and today’s date of April 15, 2024.

Related Tutorials

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

How to Compare Dates in Bash
How to Compare Two Files in Bash
How to Check if String Starts with Specific Value in Bash

Leave a Reply