Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Subtract 2 Dates

 
mike rich
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to calculate the number of days between 2 dates. I think I have confused myself beyond repair and I am seeking some advice. Below is a snip of my code. In a nutshell I am reading 2 string values, converting them to date and then I want to calculate the difference. any help would be appreciated.....
String ds1 = a[x].getinvoice().substring(date_start, last_paren);
String ds2 = a[x].getdate().trim();

DateFormat dt_parse1 = DateFormat.getDateInstance((DateFormat.SHORT));
DateFormat dt_parse2 = DateFormat.getDateInstance((DateFormat.SHORT));

try
{
Date d1 = dt_parse1.parse(ds1);
Date d2 = dt_parse1.parse(ds2);

SimpleDateFormat local_format1 = new SimpleDateFormat("MM/dd/yy");
SimpleDateFormat local_format2 = new SimpleDateFormat("MM/dd/yy");

System.out.println("New Date1: " + local_format1.format(d1));
System.out.println("New Date2: " + local_format1.format(d2));

/*Gregorian*/Calendar cal1 = new GregorianCalendar();
cal1.setTime(d1);

/*Gregorian*/Calendar cal2 = new GregorianCalendar();
cal1.setTime(d2);

System.out.println("New Date1 as calendar object: " + local_format1.format(cal1.getTime()));
System.out.println("New Date2 as calendar object: " + local_format1.format(cal2.getTime()));
System.out.println("********** " + (local_format1.format(cal1.getTime()) - local_format1.format(cal2.getTime())));


}
catch (ParseException p)
{
p.printStackTrace();
}
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mike r
Welcome to the Java Ranch, we hope you�ll enjoy visiting as a regular however,
your name is not in keeping with our naming policy here at the ranch. Please change your display name to an appropriate name as shown in the policy.
Thanks again and we hope to see you around the ranch!!
 
Marilyn de Queiroz
Sheriff
Posts: 9067
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would use some of the methods in the Date class.
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's really important to step back and think about the data types in this problem. It's a surprisingly common one.
What is the conceptual data type of the difference between two dates? If you were making a class to hold the difference between two dates, what would you call it?
Hint: it's not a Date.
 
Snigdha Solanki
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the following code:



where the input dates have format month, day,
year eg ( 6 , 2, 1983 means June 2, 1983)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic