| Author |
Subtract 2 Dates
|
mike rich
Greenhorn
Joined: Jan 30, 2002
Posts: 2
|
|
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
Joined: May 10, 2001
Posts: 3244
|
|
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!!
|
Dave
|
 |
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
|
|
|
I would use some of the methods in the Date class.
|
JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
|
 |
Frank Carver
Sheriff
Joined: Jan 07, 1999
Posts: 6919
|
|
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.
|
Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
|
 |
Snigdha Solanki
Ranch Hand
Joined: Sep 07, 2000
Posts: 128
|
|
Check out the following code: where the input dates have format month, day, year eg ( 6 , 2, 1983 means June 2, 1983)
|
Snigdha<br />Sun Certified Programmer for the Java™ 2 Platform
|
 |
 |
|
|
subject: Subtract 2 Dates
|
|
|