How to use JDK GregorianCalendar object dates with Joda

*爱你&永不变心* 提交于 2019-12-23 12:23:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!