Home > OS >  Shell script Program in linux ubuntu to find in difference between two dates
Shell script Program in linux ubuntu to find in difference between two dates

Time:12-13

I'm writing a script with these steps:

1 echo

2 echo Enter Date 1 ..(Use date format: yyyy/mm/dd)....."

3 read d1

4 echo Enter Date 2 "..... (Use date format: yyyy/mm/dd).....
 
5 read d2

6

7 echo

8 res=$(($(date -d $d2   %s) $(date -d $d1   %s)) / 86400) 

9 echo $res days

But I want to add the number of Months, Years, hours, and seconds. In my code it only displays the number of days, but I want to add Months, Years, hours and seconds to display like this:

'   ' Days
'   ' Months
'   ' Years 
'   ' Hours 
'   ' Seconds

CodePudding user response:

One solution to do this is to use the date command to first calculate the number of seconds between the two dates:

#!/bin/bash

# Prompt the user for two dates
echo "Enter Date 1 ..(Use date format: yyyy/mm/dd)....."
read d1
echo "Enter Date 2 ..(Use date format: yyyy/mm/dd)....."
read d2

# Calculate the number of seconds between the two dates
SECONDS=$(($(date -d $d2  %s) - $(date -d $d1  %s)))

# Calculate the number of months, years, hours, and seconds between the two dates
MONTHS=$((SECONDS / 2592000))
YEARS=$((SECONDS / 31536000))
HOURS=$((SECONDS / 3600))
SECONDS=$((SECONDS % 60))

# Print the results to the screen
echo "$MONTHS months"
echo "$YEARS years"
echo "$HOURS hours"
echo "$SECONDS seconds"

Here is an example:

enter image description here

  •  Tags:  
  • bash
  • Related