[Java] Date class

나르·2021년 6월 29일
0

JAVA

목록 보기
5/18
post-thumbnail

📖 Date

The class Date represents a specific instant in time, with millisecond precision.

java.lang.Object을 상속받는 클래스로, Date 클래스의 대부분이 밀레니엄 버그로 현재 Deprecated 되어 몇몇 메소드와 생성자만 주로 사용됩니다.
따라서 Date보다는 JDK 1.1 이후의 Calendar 클래스를 권장하지만, JDK 1.8부터 기존 Date API를 개선한 java.time 패키지가 제공되기 때문에 이를 사용하는 편이 좋습니다.

Date() 생성자는 컴퓨터의 현재 날짜를 읽어 Date 객체로 만듭니다.
SimpleDateFormat을 이용하면 원하는 형식을 지정할 수 있습니다.

SimpleDateFormat date = new SimpleDataFormat("yyyy년 MM월 dd일"); // 원하는 포맷의 객체 생성
SimpleDateFormat time = new SimpleDateFormat("hh:mm:ss a");

Date now = new Date(); // 기본 생성자를 호출하면 현재 날짜와 시간을 초기화
System.out.println(date.format(now)); 
System.out.println(time.format(now)); 

//결과
202106293:25:02 PM

return메소드설명
booleanafter(Date when) Tests if this date is after the specified date.
boolean before(Date when) Tests if this date is before the specified date.
object clone() Return a copy of this object.
intcompareTo(Date anotherDate) Compares two Dates for ordering.
booleanequals(Object obj) Compares two dates for equality.
StringtoString() Converts this Date object to a String of the form:
voidsetTime(long time) Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
longgetTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
intgetDate() Deprecated.
replaced by Calendar.get(Calendar.DAY_OF_MONTH).
intgetDay() Deprecated.
replaced by Calendar.get(Calendar.DAY_OF_WEEK).
intgetHours() Deprecated.
replaced by Calendar.get(Calendar.HOUR_OF_DAY).
intgetMinutes() Deprecated.
replaced by Calendar.get(Calendar.MINUTE).
intgetMonth() Deprecated.
replaced by Calendar.get(Calendar.MONTH).
intgetSeconds() Deprecated.
replaced by Calendar.get(Calendar.SECOND).
intgetTimezoneOffset() Deprecated.
replaced by -(Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000).
intgetYear() Deprecated.
replaced by Calendar.get(Calendar.YEAR) - 1900.
intparse(String s) Deprecated.
replaced by DateFormat.parse(String s).
StringtoGMTString() Deprecated.
replaced by DateFormat.format(Date date), using a GMT TimeZone.
StringtoLocaleString() Deprecated.
replaced by DateFormat.format(Date date).
static longUTC(int year, int month, int date, int hrs, int min, int sec) Deprecated.
replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec), using a UTC TimeZone, followed by Calendar.getTime().getTime().

📘 Date와 Calendar

Calendar은 달력을 표현한 abstract 클래스이기 때문에 new 연산자를 사용해서 인스턴스를 생성할 수 없습니다. 날짜와 시간을 계산하는 방법이 지역과 나라 또는 문화에 따라 다르기 때문입니다.
Calendar now = Calendar.getInstance();로 현재 운영체제에 설정되어 있는 시간대를 기준으로 한 Calendar 하위 객체를 얻을 수 있습니다.

Calendar 클래스는 일별, 주별, 월별, 년별 계산이 가능하기 때문에 달력에 관한 거의 모든 처리를 쉽게 할수 있습니다. 반면 Date 클래스는 시간, 일 에 대한 계산을 해주기 때문에 주별, 월별, 년별 계산 등을 직접 구현해줘야 합니다.

하지만 둘은 같은 단점을 공유하는데
1. 불변 객체가 아니다( not immutable)
2. int 상수 필드의 남용
3. 헷갈리는 월 지정
4. 일관성 없는 요일 상수
5. Date와 Calendar의 불편한 역할 분담

등이 있습니다. 따라서 JDK 1.8 이후로는 이러한 단점들을 개선한 java.time 패키지를 권장합니다.

참고 : https://d2.naver.com/helloworld/645609
https://madplay.github.io/post/reasons-why-javas-date-and-calendar-was-bad

📘 java.util.Date 와 java.sql.Date

util.Datesql.Date의 부모클래스입니다.
java.util.Date는 “January 1, 1970, 00:00:00 GMT”이후부터 지금까지 흐른 시간을 밀리세컨드로 환산한 값을 반환합니다.
java.sql.Date는 JDBC가 이해할 수있는 SQL 형식의 날짜 만 알려줍니다. SQL 날짜에는 년, 월, 일만 포함되며 시간 및 시간대는 없습니다.

// util => sql
java.sql.Date sqlDate = new java.sql.Date(java.util.Date.getTime());

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = simpleDateFormat.format(java.util.Date);
java.sql.Date date1 = java.sql.Date.valueOf(formattedDate);


// sql => util
java.util.Date utilDate = new java.util.Date(rs.getDate("date").getTime());
java.util.Date utilDate = rs.getTimestamp("date"); 

📘 Reference

profile
💻 + ☕ = </>

0개의 댓글