[우아한테크코스] 6월 12일 TIL

less than 1 minute read

[Spring] 시간 처리 localDatetime, Timestamp, date

mysql

  • TimeStamp
    서버의 timezone에 의존한다.
    1000-01-01 ~ 9999-12-31
  • DateTimeZone
    timezone이 반영되지 않는다.
    1970-01-01 ~ 2038-01-19
    인덱싱이 더 빠르다.

java8~

  • LocalDate
    날짜 정보만 필요할 때 사용
  • LocalTime
    시간 정보만 필요할 때 사용
  • LocalDateTime
    날짜+시간 정보가 모두 필요할 때 사용

  • DateTimeFormatter를 통해 포매팅
    LocalDate.of('2020, 12, 12').format(DateTimeFormatter.ofPattern('2021-02-26')

  • mysql의 정보 변환 방법 - jdbc 사용
    resultSet.getObject("day", LocalDateTime.class),
    column에 timestamp로 저장된 것을 LocalDateTime으로 변환하는 것

  • java의 localDate -> sql의 timestamp 변환 방법
    Timestamp.valueOf(attendance.getDate().atStartOfDay())
    localDateTime의 경우
    Timestamp.valueOf(attendance.getDateTime())

~java8

Timestamp now = new Timestamp(System.currentTimeMillis());  //여기에 string으로 sql로부터 가져온 값 넣는다.  
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = simpleDateFormat.format(now);

sql에 의존적이게 되어 좋지 않다. 구식 코드!
Timestamp(sql), Calender(util), Date(util)에 의존하는 구현

String -> Date: new SimpleDateFormat
Date -> Timestamp: new TimeStamp

Timestamp -> Date: new Date
Date -> String: new SimpleDateFormat
참고