问题
I'm trying to use Joda library since count periods with Java native methods is a pain in the neck and all my attempts give unprecise results
I have seen this sample to
int n = Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays();
since all my classes manage GregorianCalendar, I need that method that counts the days support GregorianCalendar, something like
public int countDays(GregorianCalendar start, GregorianCalendar end){
//convert to joda start and end
...
return Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays();
}
So my question:
How to convert and reconvert GregorianCalendar
object to the object managed by Joda without side effects?
回答1:
Use the DateTime
constructor that takes an Object
, which can "include ReadableInstant, String, Calendar and Date." It specifically mentions GregorianCalendar
, as well.
public int countDays(GregorianCalendar gregStart, GregorianCalendar gregEnd) {
DateTime start = new DateTime(gregStart);
DateTime end = new DateTime(gregEnd);
return Days.daysBetween(start, end).getDays();
}
回答2:
You need to get the timezone from the GragorianCalander
before creating the joda LocalDate
Something along these lines:
public int countDays(GregorianCalendar start, GregorianCalendar end){
TimeZone timeZone = start.getTimeZone();
DateTimeZone jodaTimeZone = DateTimeZone.forID(timeZone.getID());
DateTime dateTime = new DateTime(start.getTimeInMillis(), jodaTimeZone);
LocalDate startDate = dateTime.toLocalDate();
timeZone = end.getTimeZone();
jodaTimeZone = DateTimeZone.forID(timeZone.getID());
dateTime = new DateTime(end.getTimeInMillis(), jodaTimeZone);
LocalDate endDate = dateTime.toLocalDate();
return Days.daysBetween(startDate, endDate).getDays();
}
来源:https://stackoverflow.com/questions/26246030/how-to-use-jdk-gregoriancalendar-object-dates-with-joda