Java 날짜, 시간

김정훈·2024년 5월 7일

Java

목록 보기
33/48

날짜와 시간

1. Date

JDK 1.0
public class Ex01 {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date);
        int year = date.getYear();
        int month = date.getMonth(); // 0 ~ 11
        System.out.println(year + " " + month);
        long epochTime = date.getTime(); // 1970.1.1 자정, 1000분의 1초 단위로 카운팅
        System.out.println(epochTime); // UID(Unique Id)를 만들때 자주 활용
    }
}

2. Calendar

JDK 1.1

설계가 빈약
static Calendar getInstance()
서기 달력외에 다른 체계 달력(불기)을 지역화 설정에 따라 객체 생성

  • int get(날짜 시간 필드) : 날짜, 시간 조회
public class Ex02 {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        //System.out.println(cal);
        printDate(cal);
    }

    public static void printDate(Calendar cal){
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH); //0 ~ 11
        int day = cal.get(Calendar.DAY_OF_MONTH);

        System.out.println(year + " " + month + " " + day);
    }
}
  • void set(날짜 시간 필드, 값) : 날짜, 시간 변경
  • 날짜 시간 변경시 원 객체가 변경 : 불변성 유지 X
    : java.time 패키지에서 변경: 날짜 시간의 불변성 유지, 변경 할때마다 새로운 객체 반환
  • add(...) : 날짜 시간의 가감 👉 메서드명이 모호 : java.time 패키지 : plus(...), minus(...)
public class Ex01 {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        printDate(cal);
        //cal.set(Calendar.MONTH,11);
        cal.add(Calendar.DAY_OF_MONTH, 150);
        printDate(cal);
        cal.add(Calendar.DAY_OF_MONTH, -100);
        printDate(cal);
    }
}
  • roll(...) : 날짜 시간의 가감
public class Ex02 {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        //cal.add(Calendar.MONTH,30);
        cal.roll(Calendar.MONTH,30);
        printDate(cal);
    }
}

문제점

  • 설계(인터페이스 X), 체꼐 부족(상수, 기능분리X)
  • 날짜, 시간의 불변성 ❌, 변경시에 원래 객체가 변경(변경전 데이터는 확인 불가)
  • 메서드명의 모호함, 날짜 수치(월)의 모호함(월 - 0~11)

3. java.time 패키지

JDK8

1. 설계의 보완

인터페이스

  • Temporal, TemporalAccessor, TemporalAdjuster
    • LocalDate, LocalTime, LocalDateTime, ZonedDateTime, OffsetDateTime, Instant
  • TemporalAmount
    • Period, Duration
  • TemporalField : 날짜 시간 필드
    • ChronoField
  • TemporalUnit : 날짜, 시간 단위
    • ChronoUnit

2. 날짜/시간의 불변성

날짜, 시간의 변경시 👉 새로운 객체 생성

3. 메서드 명칭에서 오는 모호함을 개선(plus, minus)

4. java.time 핵심 클래스

1) Temporal, TemporalAccessor, TemporalAdjuster 인터페이스

LocalDate : 날짜
LocalDateTime atTime(시간....) : 날짜 + 시간
static LocalDate now() : 지금 현재 날짜
static LocalDate of(...) : 직접 지정한 날짜

public class Ex01 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println(today);

        LocalDate date = LocalDate.of(2023,5,8);
        System.out.println(date);
    }
}

조회
int/long get(TemporalField...)

ChronoField

참고)
Locale : 지역화

변경
with(...) : 날짜 변경
plus(...) : 날짜 더하기
minus(...) : 날짜 빼기

public class Ex02 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();

        int year = today.get(ChronoField.YEAR);
        int month = today.get(ChronoField.MONTH_OF_YEAR);
        int day = today.get(ChronoField.DAY_OF_MONTH);
        int yoil = today.get(ChronoField.DAY_OF_WEEK);//요일 1(월)~7(일)

        System.out.printf("%d, %d, %d, %d",year,month,day,yoil);

    }
}

LocalTime : 시간

  • LocalDateTime atTime(LocalDate ...) : 시간 + 날짜

LocalDateTime : 날짜(LocalDate) + 시간(LocalTime)

  • ZonedDateTime atZone(ZoneId ...) : 날짜시간 + 시간대
  • OffsetDateTime atOffset(ZoneOffset ...)

ZonedDateTime : 날짜와 시간(LocalDateTime) + 시간대(ZoneId - Asia/Seoul)

OffsetDateTime : 날짜와 시간(LocalDateTime) + 시간대(ZoneOffset - +9)

Instant : EpochTime - 1970. 1. 1 자정부터(UTC+0) 1/1000 단위 카운트 참고) Timestamp - 초 단위 카운팅

2) TemporalAmount 인터페이스

Duration : 시간 간격 (초, 나노 초)

  • between
  • until
public class Ex03 {
    public static void main(String[] args) {
        LocalTime now = LocalTime.now();
        LocalTime endTime = LocalTime.of(17,50);

        Duration du = Duration.between(now, endTime);
        System.out.println(du);
    }
}

Period : 날짜 사이의 간격(년, 월, 일)

  • between
  • until
public class Ex02 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate endDate = LocalDate.of(2024,9,30);

        Period period = Period.between(endDate, today);
        int month = period.getMonths();
        int day = period.getDays();

        System.out.println(-month + " " + -day);
    }
}

java.time.format

형식화 클래스
DateTimeFomatter

  • ofPattern("패턴")
    public class Ex04 {
       public static void main(String[] args) {
           DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss E");
           LocalDateTime startDate = LocalDateTime.of(2024,3,19,9,0);
           String strDate = formatter.format(startDate);
           System.out.println(strDate);
       }
    }

참고

핵심 클래스(LoacalDate,LocalTime,LocalDateTime...)

  • static parse(...)

format(..) : 자바 객체 👉 형식화된 문자열 변경
parse(..) : 형식화된 문자열 👉 자바 객체

public class Ex05 {
    public static void main(String[] args) {
        String strDate = "05/09/24 15:16";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yy HH:mm");
        LocalDateTime date = LocalDateTime.parse(strDate, formatter);
        System.out.println(date);
    }
}

java.time.temporal

날짜, 시간의 단위, 필드
TemporalField 인터페이스 - 필드

  • ChronoField
    TemporalUnit 인터페이스 - 단위
  • ChronoUnit

java.time.zone

시간대 관련 클래스
ZoneId

ZoneOffset

1. java.time 패키지의 핵심 클래스

1. LocalDate와 LocalTime

  • 특정 필드의 값 가져오기 - get(), getXXX()
    int get(필드 명);
    ChronoField : 날짜, 시간 필드

  • 필드의 값 변경하기 - with(), plus(), minus()
    LocalDate with() : 날짜/시간 변경
    LocalDate plus() : 날짜/시간 +
    LocalDate minus() : 날짜/시간 -

  • 날짜와 시간의 비교 - isAfter(), isBefore(), isEqual()
    - compareTo() : 음수 - isBefore()
    - compareTo() : 0 - isEqual()
    - compareTo() : 양수 - isAfter()

2. Period와 Duration

3. 객체 생성하기 - now(), of()

now() : 현재 날짜,시간 
of(....)

4. Temporal과 TemporalAmount

5. Instant

파싱과 포맷

java.time.format

1. parse()

형식화 문자열 -> 날짜/시간

  • 핵심 클래스 (LocalDate, LocalTime, LocalDateTime ... )

2. format() : 날짜/시간 -> 형식화 문자열

DateTimeFormatter
DateTimeFormatter state ofPattern("패턴")
.format(TemporalAccessor ...)

				
profile
안녕하세요!

0개의 댓글