Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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 31
Tags
more
Archives
Today
Total
관리 메뉴

DOing

[JAVA] LocalDate, LocalTime, LocalDateTime 정리 본문

Java & Kotlin

[JAVA] LocalDate, LocalTime, LocalDateTime 정리

mangdo 2021. 8. 12. 15:21

 

  • LocalDate : 날짜 타입
  • LocalTime : 시간 타입
  • LocalDateTime : 날짜 + 시간 타입

 

💡 현재 시간 알아내기

public class Main {
    public static void main(String[] args) {
        System.out.println("현재 시간 알아내기");
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
        LocalDateTime dateTime = LocalDateTime.now();

        System.out.println(date); // 2021-08-12
        System.out.println(time); // 12:30:33.0000021
        System.out.println(dateTime); // 2021-08-12T12:30:33.0000021
    }
}

 

💡 시간 지정하기

of()을 이용해서 시간 혹은 날짜를 직접 지정할 수 있다.

public class Main {
    public static void main(String[] args) {

        System.out.println("of()로 특정시간 지정");
        LocalDate newDate = LocalDate.of(2021, 08, 20); // 년, 월, 일
        LocalTime newTime = LocalTime.of(22, 50, 00); // 시, 분, 초

        System.out.println(newDate); // 2021-08-20
        System.out.println(newTime); // 22:50
    }
}

 

💡 시간의 형식 수정

format()을 이용해서 형식을 수정할 수 있다.

이외에 다양한 형식들은 자바 공식문서를 통해 확인할 수 있다.

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

public class Main {
    public static void main(String[] args) {

        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT); // 오전 오후 표시
        String shortFormat = formatter.format(LocalTime.now());
        System.out.println(shortFormat); // 10:22 PM
        
        // 직접 형식을 지정할 수도 있다.
        DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy년MM월dd일");
        // DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd일");
        
        String myDate = newFormatter.format(LocalDate.now());
        System.out.println(myDate); // 2021년08월12일
        
    }       
}

 

💡 String -> LocalDate

parse()를 이용해서 String에서 시간/날짜 형식으로 변경할 수 있다.

LocalDate date1 = LocalDate.parse("2021-08-12");

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate date2 = LocalDate.parse("2021/08/12", formatter);

 

💡 시간 차이

between()을 이용해서 시간 혹은 날짜 차이를 알아낼 수 있다.

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(2021, 8, 9);
Period period = Period.between(today, birthday);

System.out.println(period.getMonths()); // 몇 달이 지났는지
System.out.println(period.getDays()); // 몇 일이 지났는지

 

 

'Java & Kotlin' 카테고리의 다른 글

[Java] 리스트 내 요소 중복 체크  (0) 2021.09.14
[JAVA] 컬렉션 정리  (0) 2021.08.12
[JAVA] 예외처리  (0) 2021.06.24
[JAVA] 객체 지향 언어2  (0) 2021.06.24
[IntelliJ] unmappable character for encoding MS949 에러  (3) 2021.06.24