0

I am new in java. I have two dates like as Fri Sep 25 00:00:00 IST 2015 and Fri Oct 23 00:00:00 IST 2015. I am trying to get week difference so output will be :-

Sep 25-Oct 1 2015, Oct 2-8 2015, Oct 9-15 2015, Oct 16-21 2015, Oct 22-23 2015

Please help me! I do not want to use joda time

Rahul Rawat
  • 13
  • 1
  • 6

2 Answers2

1

Acording to http://www.leveluplunch.com/java/examples/number-of-weeks-between-two-dates/ In Java 8:

public void weeks_between_two_dates_in_java_with_java8 () {

    LocalDate startDate = LocalDate.of(2005, Month.JANUARY, 1);
    LocalDate endDate = LocalDate.of(2006, Month.JANUARY, 1);

    long weeksInYear = ChronoUnit.WEEKS.between(startDate, endDate);

    assertEquals(52, weeksInYear);
}

Java 8 has pretty good API for date & time, and as you can see http://www.joda.org/joda-time/

Joda-Time is the de facto standard date and time library for Java. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).

dawidklos
  • 902
  • 1
  • 9
  • 32
0

In this thread you could see how to get date difference.

So based on the thread I told you, you can transform difference on weeks this way:

long diff = d2.getTime() - d1.getTime();
int weeks = diff / (7 * 24 * 60 * 60 * 1000 );

Which correspond to 7 days per 24 hours per 60 minutes per 60 seconds per 1000 miliseconds.

Community
  • 1
  • 1
malaguna
  • 4,183
  • 1
  • 17
  • 33
  • It can be done more ellegant way. This solution is not very readable. – dawidklos Sep 25 '15 at 12:08
  • 1
    @d__k I don't think this solution is less elegant. It is not dependent on any Java version nor library dependency. It is straightforward and it can be well encapsulated and thus used in an elegant way. – malaguna Sep 25 '15 at 12:10
  • Thanks. can we have this format? sep 25-Oct 1 2015, Oct 2-8 2015, Oct 9-15 2015, Oct 16-21 2015, Oct 22-23 2015 – Rahul Rawat Sep 25 '15 at 12:11