Recipe Name:
Migrate new GregorianCalendar (Timezone, Locale) to java.time
Description:
Migrate new GregorianCalendar (Timezone, Locale) to java.time
Level:
warning
Language:
  • java
Tags:
  • java.time
  • java.util.Calendar
  • quality
Documentation

Migrate from java.util.Date and java.util.Calendar to Java Time

Prior to the Java SE 8 release, the Java date and time mechanism was provided by the java.util.Date, java.util.Calendar, and java.util.TimeZone classes, as well as their subclasses, such as java.util.GregorianCalendar.

These classes had several drawbacks, including:

  • The Calendar class was not type safe.
  • Because the classes were mutable, they could not be used in multithreaded applications.
  • Bugs in application code were common due to the unusual numbering of months and the lack of type safety.

Perhaps you have legacy code that uses the java.util date and time classes and you would like to take advantage of the java.time functionality with minimal changes to your code.

Examples

Before
    Calendar calendar = new GregorianCalendar(2020, 05, 10, 10, 30);
    calendar.add(Calendar.YEAR, 1);
After
    LocalDateTime calendar = LocalDateTime.of(2020, 05, 10, 10, 30);
    calendar.plusYears(1);
References
Recipe
id: scw:gregorian-calendar:constructor-locale-timezone
version: 10
metadata:
  name: Migrate new GregorianCalendar (Timezone, Locale) to java.time
  shortDescription: Migrate new GregorianCalendar (Timezone, Locale) to java.time
  level: warning
  language: java
  enabled: true
  comment: This recipe doesn't use java.util.Locale. It generates a java.time.ZonedDateTime or java.time.OffsetDateTime using only java.time.ZoneId previously converted.
  descriptionFile: Java/Date-Calendar/descriptions/date-calendar.html
  tags: java.time;java.util.Calendar;quality
search:
  instanceCreation:
    args:
      1:
        anyOf:
        - type: java.time.ZoneId
        - type: java.util.TimeZone
      2:
        type: java.util.Locale
    type: java.util.GregorianCalendar
availableFixes:
- name: Migrate to java.time.ZonedDateTime
  actions:
  - rewrite:
      to: java.time.ZonedDateTime.now({{{ arguments.0 }}})
  - modifyAssignedVariable:
      type: java.time.ZonedDateTime
- name: Migrate to java.time.OffsetDateTime
  actions:
  - rewrite:
      to: java.time.OffsetDateTime.now({{{ arguments.0 }}})
  - modifyAssignedVariable:
      type: java.time.OffsetDateTime