티스토리 뷰

728x90

2021.03.25 - [Java] - JAVA8 java.time 훑어보기 - (1)

 

지난번에 이어 이번에는 날짜와 시간을 비교하고 간격을 나타낼때 사용하는 클래스와 날짜를 포매팅하는 방법에 대해서 작성

시간 간격을 알기 위해서는 Duration과 Period를 사용할 수 있는데 Duration을 시간 간격을 Period는 날짜 간격을 구할 때 사용한다.

Duration

Duration은 두 시간 객체사이의 간격을 알고싶을 때 사용한다. between 정적 메서드를 사용한다.

private static void DurationPrint() {
    LocalTime startTime = LocalTime.of(15, 42);
    LocalTime endTime = LocalTime.of(16, 42);

    Duration between = Duration.between(startTime, endTime);
    System.out.println("초 간격 = " + between.getSeconds());
    System.out.println("나노 초 간격 = " + between.getNano());
    System.out.println("간격이 음수인지 확인 = " + between.isNegative());
    System.out.println("간격이 0인지 확인 = " + between.isZero());
}
//결과
초 간격 = 3600
나노 초 간격 = 0
간격이 음수인지 확인 = false
간격이 0인지 확인 = false

Period

Period는 두 날짜 사이의 간격을 알고싶을 때 사용한다. between 정적 메서드를 사용한다.

만약 get() 메서드를 사용한다면 Temporal 인터페이스를 구현한 ChronoUnit(열거형) 을 사용하면 된다.

private static void PeriodPrint() {
    LocalDate startDate = LocalDate.of(2021,3,11);
    LocalDate endDate = LocalDate.of(2021, 4, 15);

    Period between = Period.between(startDate, endDate);
    System.out.println("년간격 = " + between.getYears());
    System.out.println("월간격 = " + between.getMonths());
    System.out.println("일자간격 = " + between.getDays());
    System.out.println("between.getUnits() = " + between.getUnits());
    System.out.println("between.get(ChronoUnit.DAYS) = " + between.get(ChronoUnit.DAYS));
}
//결과
년간격 = 0
월간격 = 1
일자간격 = 4
between.getUnits() = [Years, Months, Days]
between.get(ChronoUnit.DAYS) = 4

출처 - 모던자바인액션 Duration과 Period 클래스가 공통으로 제공하는 메서드

until() 정적메서드로 날짜,시간 차이 구하기

LocalDate와 LocalTime 그리고 LocalDateTime에 모두 있는 until() 정적 메서드로 날짜와 시간 간격을 구할수도 있다.

Period until(ChronoLocalDate endDateExclusive)
long until(Temporal endExclusive, TemporalUnit unit);

파라미터로 하나만 넘어가는 until 메서드는 Period를 반환하고 두개를 넘기는 until 메서드는 long형을 반환한다.

private static void useUntilStaticMethod() {
    LocalDate startDate = LocalDate.of(2021, 3, 11);
    LocalDate endDate = LocalDate.of(2021, 4, 15);
    Period period = startDate.until(endDate);
    System.out.println(period.getYears());  //0
    System.out.println(period.getMonths()); //1
    System.out.println(period.getDays());   //4

    LocalTime startTime = LocalTime.of(15, 42);
    LocalTime endTime = LocalTime.of(16, 42);
    long until = startTime.until(endTime, ChronoUnit.HOURS);
    System.out.println(until);  //1
}

파라미터가 두 개가 들어가는 until 정적 메서드의 첫번째 파라미터 타입인 Temporal 인터페이스는 LocalTime, LocalDate, LocalDateTime 클래스가 모두 구현하고있으므로 예제코드에서는 LocalTime을 넘기지만 LocalDate나 LocalDateTime을 넘겨도 상관없다. 

전체 시간 차이 구하기

between() 메서드는 Period와 Duration 클래스, 그리고 ChronoUnit 열거 타입에도 있다.

Period와 Duration의 between()은 년, 달, 일 초의 단순 차이를 리턴하고, ChronoUnit 열거 타입의 between()은 전체 시간을 기준으로 차이를 리턴한다.

private static void useChronoUnitBetween() {
    LocalDateTime startDateTime = LocalDateTime.of(2021, 3, 15, 15, 30);
    LocalDateTime endDateTime = LocalDateTime.of(2021, 4, 30, 15, 30);

    long remainYear = ChronoUnit.YEARS.between(startDateTime, endDateTime);
    long remainMonth = ChronoUnit.MONTHS.between(startDateTime, endDateTime);
    long remainDay = ChronoUnit.DAYS.between(startDateTime, endDateTime);
    long remainHour = ChronoUnit.HOURS.between(startDateTime, endDateTime);
    long remainSecond = ChronoUnit.SECONDS.between(startDateTime, endDateTime);

    System.out.println("remainYear = " + remainYear);
    System.out.println("remainMonth = " + remainMonth);
    System.out.println("remainDay = " + remainDay);
    System.out.println("remainHour = " + remainHour);
    System.out.println("remainSecond = " + remainSecond);
}
//결과
remainYear = 0
remainMonth = 1
remainDay = 46
remainHour = 1104
remainSecond = 3974400

날짜 포매팅

날짜와 시간 클래스는 문자열을 파싱(parsing) 해서 날짜와 시간을 생성하는 메소드와 이와 반대로 날짜와 시간을 포매팅(Formatting) 된 문자열로 반환하는 메소드를 제공한다.

parse() 메소드

문자열을 날짜와 시간으로 파싱하려면 parse() 메소드를 사용한다.

parse() 메소드는 기본적으로 ISO_LOCAL_DATE 포매터를 사용해서 문자열을 파싱한다. ISO_LOCAL_DATE 형식은 yyyy-MM-dd 형식이다.

public static LocalDate parse(CharSequence text) {
    return parse(text, DateTimeFormatter.ISO_LOCAL_DATE);
}

public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
    Objects.requireNonNull(formatter, "formatter");
    return formatter.parse(text, LocalDate::from);
}

만약 다른 문자열을 파싱하고 싶다면 DateTimeFormatter의 ofPattern() 메서드를 정의해서 사용할수도 있다.

그러나 DateTimeFormatter 에 표준화된 포매터가 이미 많이 정의되어있으므로 ofPattern() 을 굳이 사용하지 않아도 된다.

 

출처 - 자바의 정석 3판 파싱과 포맷

예제로 확인

private static void parsingAndFormatter() {
    LocalDate parse = LocalDate.parse("2021-03-25");
    System.out.println("parse = " + parse);

    LocalDate parse1 = LocalDate.parse("2021-04-25", DateTimeFormatter.ISO_LOCAL_DATE);
    System.out.println("parse1 = " + parse1);

    LocalDate parse2 = LocalDate.parse("2021/04/25", DateTimeFormatter.ofPattern("yyyy/MM/dd"));
    System.out.println("parse2 = " + parse2);
}
//결과
parse = 2021-03-25
parse1 = 2021-04-25
parse2 = 2021-04-25

문자열 날짜를 받아와서 LocalDate 객체로 변환했다. 이렇게 LocalDate 객체로 변환해서 날짜 값을 조작하거나 변경할 수 있다.

마지막 parse2는 yyyy/MM/dd 형식으로 들어온 문자열을 DateTimeFormatter.ofPattern() 을 사용했다. 

format() 메소드

반대로 날짜 객체를 문자열로 바꾸려면 format() 메소드를 사용한다.

@Override  // override for Javadoc and performance
public String format(DateTimeFormatter formatter) {
    Objects.requireNonNull(formatter, "formatter");
    return formatter.format(this);
}

format() 메소드의 파라미터 DateTimeFormatter 에 넘긴 형식대로 문자열을 반환한다.

private static void formatDate() {
    LocalDateTime now = LocalDateTime.now();
    String format = now.format(DateTimeFormatter.ISO_LOCAL_DATE);
    System.out.println("format = " + format);

    String format1 = now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    System.out.println("format1 = " + format1);
}
//결과
format = 2021-03-25
format1 = 2021-03-25T17:46:11.065524

참고

이것이 자바다 www.yes24.com/Product/Goods/15651484?OzSrank=2

 

자바의 정석 www.yes24.com/Product/Goods/24259565?OzSrank=2

 
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함