Calculating the number of days between 1900-01-01
and a date after 1918-03-24
using Joda-Time seems to give an off-by-one result.
Using Java 8 java.time
gives the correct result. What is the reason for Joda-Time not counting 1918-03-25
?
Using Joda-time v2.9.9.
public static void main(String[] args) {
jodaDiff("1918-03-24");
javaDiff("1918-03-24");
jodaDiff("1918-03-25");
javaDiff("1918-03-25");
jodaDiff("1918-03-26");
javaDiff("1918-03-26");
jodaDiff("2017-10-10");
javaDiff("2017-10-10");
}
private static void jodaDiff(String date) {
DateTime start = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeZone.forID("UTC"));
DateTimeFormatter dateDecoder = DateTimeFormat.forPattern("YYYY-MM-dd");
DateTime end = dateDecoder.parseDateTime(date);
int diff = Days.daysBetween(start, end).getDays();
System.out.println("Joda " + date + " " + diff);
}
private static void javaDiff(String date) {
LocalDate start = LocalDate.parse("1900-01-01");
LocalDate end = LocalDate.parse(date);
int diff = (int) ChronoUnit.DAYS.between(start, end);
System.out.println("Java " + date + " " + diff + "\n");
}
Output:
Joda 1918-03-24 6656
Java 1918-03-24 6656Joda 1918-03-25 6656
Java 1918-03-25 6657Joda 1918-03-26 6657
Java 1918-03-26 6658Joda 2017-10-10 43015
Java 2017-10-10 43016
The problem is that your DateTimeFormatter
is using the system default time zone. Ideally, you should parse to LocalDate
values instead of DateTime
, but you can fix it by using UTC for the formatter anyway:
DateTimeFormatter dateDecoder = DateTimeFormat.forPattern("YYYY-MM-dd").withZoneUTC();
To parse with LocalDate
instead, just use:
org.joda.time.LocalDate start = new org.joda.time.LocalDate(1900, 1, 1);
DateTimeFormatter dateDecoder = DateTimeFormat.forPattern("YYYY-MM-dd");
org.joda.time.LocalDate end = dateDecoder.parseLocalDate(date);
(Obviously you don't need to fully-qualify it if you're not using Java 8.)
See more on this question at Stackoverflow