0

I am trying to make a UNIX script that calculates how many days and hours are left until a birthday that the user inputs. I am only able to get the user to input his birthday and separate it into days month and year and the current date info but i think i'm doing the subtraction wrong

echo -n "Enter the birthdate (mm-dd-yyyy): "
read bdate
bmonth=${bdate:0:2}
bday=${bdate:3:2}
byear=${bdate:6:4}`
`cdate='date +%m-%d-%Y'/
cmonth=${cdate:0:2}
cday=${cdate:3:2}
cyear=${cdate:6:4}
diffdays=$(( ($bdate - $cdate) / (60*60*24) ))
echo $difdays
Johan
  • 69
  • 2
  • 8
  • 1
    You'll probably want to use the date format sequence `%j` -- check the man page for meaning. – glenn jackman Feb 17 '19 at 13:43
  • At the line where you do the subtraction, what is the value of `$bdate` (and `$cdate`)? Is it a single integer? – glenn jackman Feb 17 '19 at 13:44
  • 1
    See: [How to find the difference in days between two dates?](https://stackoverflow.com/q/4946785/3776858) – Cyrus Feb 17 '19 at 14:40
  • Add a shebang and then paste your script there: http://www.shellcheck.net – Cyrus Feb 17 '19 at 14:45
  • Your attempt doesn't take into account that months don't have a single fixed size. There are fewer days between February 10th and March 10th than between March 10th and April 10th, for example. – chepner Feb 17 '19 at 18:03
  • cf. second half of https://www.youtube.com/watch?v=qHDSNs9wBpU – jhnc Feb 17 '19 at 19:07
  • 1
    What do you mean by "birthdate"? If I was born on 1970-01-01, is birthdate in this context "1970-01-01" or "2020-01-01" ? – jhnc Feb 17 '19 at 19:13
  • When you say "how many [..] hours are left", even if you are assuming birthday begins on the first second of the date in question, per the video, you still need to know the timezones of place of birth and current location. Without it, even days left can be wrong by one. – jhnc Feb 17 '19 at 19:19

1 Answers1

0

The below is working.

#!/bin/bash
## Just using a YYYY-MM-DD format
echo -n "Enter the birthdate (YYYY-MM-DD):"
read bdate
## convert to epoch time
bdate=`date -d "${bdate}" +"%s"`
## convert to epoch time
current_date=`date  +"%s"`
## perform a calculation divide to find the no. of days
echo $(($((bdate - current_date)) / 86400))
error404
  • 2,684
  • 2
  • 13
  • 21
  • You seem to be assuming date of next anniversary of birth. Usually birthdate will be in the past. – jhnc Feb 17 '19 at 19:12
  • Yes, I guess thats what has been asked. We have to calculate the days until the exact birthday from the current date. Assuming the birthday date is greater than the current date. – error404 Feb 18 '19 at 04:48