0

Two friends want to know HOW MUCH OLDER the first friend is compared to the second friend. Write a program that will determine the number of days between their two birthdays, assuming the birthdays follow the format MMDD and that both friends are born on the same year.

I am new to programming and I need help in answering this question! Thanks!

user2864740
  • 60,010
  • 15
  • 145
  • 220
Belle
  • 15
  • 1
  • 4
  • You should probably look at how you can convert strings to dates. Let us know if you have any issues. Also, you should probably use `LocalDate` (from Joda-Time library) instead of Java's `Date` class – TheLostMind Sep 01 '15 at 06:26

1 Answers1

0

Program to calculate no of days between two dates :

import java.util.Date;
class Example{
public int numberOfDays(String fromDate,String toDate)
{    
   java.util.Calendar cal1 = new java.util.GregorianCalendar();
   java.util.Calendar cal2 = new java.util.GregorianCalendar();

   //split year, month and days from the date using StringBuffer.
   StringBuffer sBuffer = new StringBuffer(fromDate);
   String yearFrom = sBuffer.substring(6,10);
   String monFrom = sBuffer.substring(0,2);
   String ddFrom = sBuffer.substring(3,5);
   int intYearFrom = Integer.parseInt(yearFrom);
   int intMonFrom = Integer.parseInt(monFrom);
   int intDdFrom = Integer.parseInt(ddFrom);

   // set the fromDate in java.util.Calendar
   cal1.set(intYearFrom, intMonFrom, intDdFrom);

   //split year, month and days from the date using StringBuffer.
   StringBuffer sBuffer1 = new StringBuffer(toDate);
   String yearTo = sBuffer1.substring(6,10);
   String monTo = sBuffer1.substring(0,2);
   String ddTo = sBuffer1.substring(3,5);
   int intYearTo = Integer.parseInt(yearTo);
   int intMonTo = Integer.parseInt(monTo);
   int intDdTo = Integer.parseInt(ddTo);

   // set the toDate in java.util.Calendar
   cal2.set(intYearTo, intMonTo, intDdTo);

   //call method daysBetween to get the number of days between two dates
   int days = daysBetween(cal1.getTime(),cal2.getTime());
   return days;
   }

   //This method is called by the above method numberOfDays
   public int daysBetween(Date d1, Date d2)
   {
    return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
   }
   public static void main(String args[]){
   Example obj= new Example();
   int num= obj.numberOfDays("04-19-2013", "07-19-2013");
   System.out.println("Number of days between mentioned dates are: "+num);
  }
 }
Himanshu Singh
  • 84
  • 1
  • 13