0

I want to find out from the startDate and endDate how many days is it. From my json response, I can get back these in String:

String startDate = "Fri, 10 Jan 2015 23:10:04 +0000";
String endDate = "Mon, 26 Jan 2015 11:26:04 +0000";

How would I use joda to calculate and get me back the correct number of days (hence: numOfDays = endDate - startDate) ??

public int getNumberOfDays(String startDate, String endDate) {
    String pattern = "EEE, dd MMM yyyy HH:mm:ss +xxxx";
    .....

    // quick test on startDate
    DateTime dateTime = DateTime.parse(startDate, DateTimeFormat.forPattern(pattern));
    System.out.println("The day should be 10 but it yields 9 --> " + dateTime.getDayOfMonth());

}
user2763948
  • 91
  • 1
  • 1
  • 7
  • String startDate = "Fri, 10 Jan 2015 23:10:04 +0000"; String pattern = "EEE, dd MMM yyyy HH:mm:ss +xxxx"; Does anyone know if the pattern is correct? I am struggling to parse the 'EEE' correct and I don't know if it has to do with that or the ',' comma. If I remove "Fri," hence the "EEE," then I am able to get the day (10) correctly. – user2763948 Jan 28 '15 at 17:30

1 Answers1

1

Use Days Class of Joda Library

Days days=Days.daysBetween(startDate.toLocalDate(), endDate.toLocalDate()).getDays();
int noOfDays=days.getDays();

As an alternative we can also ues Java 8 Date and Time API

public void days_between_two_dates_in_java_with_java8 () {

    LocalDate startDate = LocalDate.now().minusDays(1);
    LocalDate endDate = LocalDate.now();

    long days = Period.between(startDate, endDate).getDays();


    // or 

    long days2 = ChronoUnit.DAYS.between(startDate, endDate);

}
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62