Recipe Name:
Migrate Calendar set() to java.time with() - Months
Description:
Migrate Calendar set() to java.time with() - Months
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:calendar:set-month
version: 10
metadata:
  name: Migrate Calendar set() to java.time with() - Months
  shortDescription: Migrate Calendar set() to java.time with() - Months
  level: warning
  language: java
  enabled: true
  comment: We have different results from java.util.Calendar.MONTH and java.time Month. While Calendar Lib is 0-based (Jan = 0), java.time has Jan index equals 1. Be aware that this recipe adds 1 in argument to keep code working. It's up to user to refactor this later.
  descriptionFile: Java/Date-Calendar/descriptions/date-calendar.html
  tags: java.time;java.util.Calendar;quality
search:
  methodcall:
    args:
      1:
        referenceTo:
          name: java.util.Calendar.MONTH
      2:
        type: int
    name: set
    anyOf:
    - type: java.time.LocalDate
    - type: java.time.LocalDateTime
    - type: java.time.ZonedDateTime
    - type: java.time.OffsetDateTime
availableFixes:
- name: Rewrite using java.time withMonth
  actions:
  - rewrite:
      to: '{{{ qualifier }}} = {{{ qualifier }}}.withMonth({{{ arguments.1 }}} + 1)'