Two Laptop Bag*
The moose likes Beginning Java and the fly likes Date difference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Date difference" Watch "Date difference" New topic
Author

Date difference

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1371
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
String startdate = dateFormat.format(new Date());
String = enddate;
I want to find out the number of days between these two dates,but these two dates are in String format. How can i do that?
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281


java amateur
Jeff Jetton
Ranch Hand

Joined: Mar 29, 2005
Posts: 71
Originally posted by miguel lisboa:


Wouldn't that only work as long as the two dates are in the same year? If you set it up like this:

String sData1 = "31/12/2004";
String sData2 = "1/1/2005";

You'd get 364 instead of 1, wouldn't you?

One way to do it, as long as your dates are both after 1/1/1970, is to convert your strings to Date objects, using either DateFormat or SimpleDateFormat like Miguel did. Then use the getTime() method on those dates to get their values in milliseconds. Subtract the two, then divide the result by 86400000 (milliseconds in a day).

- Jeff
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
Wouldn't that only work as long as the two dates are in the same year?

that's what i had in mind, but you'r absolutely right!
kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1371
Try this code, i am not getting the exact difference....It shows difference between Apr 3 and Apr 4th value is 0. (instead of 1)
kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1371
Any reply ??
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
Before you do the difference round each date to the beginning of the day. As long as you don't have to worry about getting dates from different time zones that should work.
kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1371
Hi Steven, How can i get the begining of the day??
kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1371
I got the exact reult. I used getDateTimeInstance() instead of getDateInstance().
kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1371
One more thing, pass the Strign like this..
String yesdate = "3/3/05 0:0 AM, IST";
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Date difference
 
Similar Threads
Validating date using regex and simple date format
calculate with dates
Dates and Times confusion (again)
compare two dates
How to compare two dates