Java/개념

[Java] Date, Calendar클래스가 왜 Deprecated됐는지?

TheWing 2020. 11. 2. 18:03

Java 에서 Date클래스와 Calendar 클래스가 왜 Deprecated 됐는지?

  • 앞 전 포스팅으로 이어서 포스팅하겠습니다.

2020/11/02 - [Java/개념] - Java Date와 Calendar 클래스

국제화와 잘 맞지 않는다

  • java.util.Date 클래스는 실제로 더 이상 사용되지 않으며, 생성자와 다른 생성자/메소드도 더 이상 사용되지 않는다. 그것은 국제화와 잘 맞지 않기 때문에 더 이상 사용되지 않았다. Calendar클래스는 대신 다음과 같이 사용해야한다.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date dateRepresentation = cal.getTime();
  • 또한 Date를 리턴하는 메서드인 Calendar.getInstance().getTime() 이 모호함으로 반환 타입을 예측을 할 수가 없다.
  • 앞 전 포스팅에서 설명했듯이 많은 상수들이 있는데 메서드를 사용할 때 상수의 이름으로 리턴 타입을 예측하지 못 할 수 있다.

월(Month) 계산

  • 월(Month) 계산이 힘들 수 있다. 월을 표기를 하는 상수 값들을 확인해보면 1월은 0이다 12월은 11이기 때문에 -1을 사용해서 가독성을 높여줘야한다.
/**
 * Value of the {@link #MONTH} field indicating the
 * first month of the year in the Gregorian and Julian calendars.
 */
public static final int JANUARY = 0;

/**
 * Value of the {@link #MONTH} field indicating the
 * second month of the year in the Gregorian and Julian calendars.
 */
public static final int FEBRUARY = 1;

/**
 * Value of the {@link #MONTH} field indicating the
 * third month of the year in the Gregorian and Julian calendars.
 */
public static final int MARCH = 2;

/**
 * Value of the {@link #MONTH} field indicating the
 * fourth month of the year in the Gregorian and Julian calendars.
 */
public static final int APRIL = 3;

/**
 * Value of the {@link #MONTH} field indicating the
 * fifth month of the year in the Gregorian and Julian calendars.
 */
public static final int MAY = 4;

/**
 * Value of the {@link #MONTH} field indicating the
 * sixth month of the year in the Gregorian and Julian calendars.
 */
public static final int JUNE = 5;

/**
 * Value of the {@link #MONTH} field indicating the
 * seventh month of the year in the Gregorian and Julian calendars.
 */
public static final int JULY = 6;

mutable 하다

  • mutable 이란 값이 변한다는 의미
  • Immutable 이란 값이 변하지 않다는 의미 불변이다
  • 대표적으로 String 클래스가 Immutable이다
  • Immutable 하지 않는다. Date 객체나 Calendar 객체가 다른 쪽에서 공유하여 사용하게되면 변경될 때 값이 일치하지 않게되며 값에 영향을 줄 수있다.

 

 

다음 포스팅은 Java8에서 새로 추가된 LocalDate, LocalTime, LocalDateTime 에 대해 알아보겠습니다.