What is "jodatime"
The Joda-time was created by Stephen Colebourne, and before Java 8 was released, it was an excellent alternative to the native date API (java.util.Date
and java.util.Calendar
). No wonder its author was also the leader of JSR-310, which resulted in the new Java 8 Date API (java.time
).
Among the improvements regarding Date
and Calendar
, we can quote:
- different types of date and time for different situations (
LocalDate
for dates only,DateTime
for dates, times in a specific Timezone, etc) - January is month 1 (in the previous API January is month zero, which caused a lot of confusion)
- Fluid and intuitive API. Ex:
DateTime datetime = new LocalDateTime(2018, 3, 10, 10, 30) // 10/03/2018, 10:30 da manhã
// somar 10 dias
.plusDays(10)
// no timezone da Alemanha
.toDateTime(DateTimeZone.forID("Europe/Berlin"))
// menos 3 horas
.minusHours(3);
System.out.println(datetime); // 2018-03-20T07:30:00.000+01:00
// compatibilidade com java.util.Date
Date date = datetime.toDate();
Just to compare, the same code with Date
and Calendar
would be:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
// nesta API, março é o mês 2
cal.set(2018, 2, 10, 10, 30, 0); // 10/02/2018, 10:30 da manhã
// getInstance() cria um Calendar com a data e hora atual, então não esqueça de setar os milissegundos para zero
// (no Joda-time não foi necessário, porque o construtor de LocalDateTime já setou para zero)
cal.set(Calendar.MILLISECOND, 0);
// somar 10 dias
cal.add(Calendar.DAY_OF_MONTH, 10);
// subtrair 3 horas
cal.add(Calendar.HOUR_OF_DAY, -3);
Date date = cal.getTime();
For more details, see documentation.
Despite being an excellent API, on your own site there is a warning recommending the use of java.time
:
Note that Joda-Time is considered to be a largely "finished" project. No major Nhancements are Planned. If using Java SE 8, Please migrate to java.time (JSR-310).
Note that Joda-time is considered a "finished" project. There are no major improvements planned. If you are using Java SE 8, please migrate to java.time (JSR-310).
For those using JDK 6 or 7, an alternative is to use Threeten Backport, an excellent backport of java.time
, with virtually all major API functionalities.
However, for JDK <= 5, Joda-time is still an excellent alternative to native classes Date
and Calendar
.
For a more detailed analysis, see: Why should I use Joda-Time?. And to help you decide, take a look at the API java.time
, in How to migrate from Date
and Calendar
for the new Java 8 Date API?.