3

I have a code that has 2 dates in the format

DateFormat dateFormat= new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
           Date date=new Date();

           DateFormat formatter ; 
           Date publishDate = (Date)dateFormat.parse(pubDate);  

I want to calculate days between two dates. I can't use Joda package. Is there any way to get the day difference in the 2 dates ?

3
  • Why don't you want to use Joda package? Commented May 18, 2012 at 17:29
  • I have some restrictions. Is there any other way ? Commented May 18, 2012 at 17:30
  • Check answers here : stackoverflow.com/questions/3299972/… . The 4th is what you may need Commented May 18, 2012 at 17:31

2 Answers 2

4

Date d1 = ..., d2 = ...;
long t1 = d1.getTime(),
   t2 = d2.getTime();
long day = 1000 * 60 * 60 * 24; // milliseconds in a day
return (t1 - t2) / day;
Sign up to request clarification or add additional context in comments.

2 Comments

You need to normalize the Date objects millis by making them equal to the same point in the day; ex: 12AM for this approach to be 100% accurate.
it depends what the specifications are. But sure
1

You can just subtract the millis between the 2 dates and then divide by number of millis per day

3 Comments

You need to normalize the Date objects millis by making them equal to the same point in the day; ex: 12AM for this approach to be 100% accurate.
And Daylight Wastings Time can affect the result too.
Yes, I was just giving a general idea of how to do it. There are definite issues with daylight savings times and other time oddities which make time difficult to deal with. My original thought would have been to just use JODA, but the OP said they cannot use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.