Joda-Time

Posted by Bruce Tsai
05/16/2016

日期與時間的處理在 Java 上一直以來有許許多多的陷井困難,由最早的 DateCalendar,都存在不少的問題,對時間處理有愛恨情仇的可以參考這篇的內容 【Joda-Time 與 JSR310 】(1)Date 與 Calendar 怎麼了?。因為日期的處理困難,理所當然地就會有好事者開發第三方類別庫來替代原本的日期 API,較著名的如 Joda-Timedate4jJoda-Time 提供了日期時間的運算、傳統曆法的處理等等。在 JDK7 前的時間處理上,在可能的情況下儘量使用 Joda-Time 以避免踩到地雷,若是 JDK8 以上,則可以依 JSR310 規範使用 Java 新的日期 API。

public boolean isAfterPayDay(DateTime datetime) {
  if (datetime.getMonthOfYear() == 2) {   // February is month 2!!
    return datetime.getDayOfMonth() > 26;
  }
  return datetime.getDayOfMonth() > 28;
}

public Days daysToNewYear(LocalDate fromDate) {
  LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1);
  return Days.daysBetween(fromDate, newYear);
}

public boolean isRentalOverdue(DateTime datetimeRented) {
  Period rentalPeriod = new Period().withDays(2).withHours(12);
  return datetimeRented.plus(rentalPeriod).isBeforeNow();
}

public String getBirthMonthText(LocalDate dateOfBirth) {
  return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH);
}

results matching ""

    No results matching ""