[JAVA] LocalDate()

myminimin·2023년 7월 26일
0

JAVA

목록 보기
11/21

코딩테스트를 하는데 다른 이용자의 답안을 보니 이렇게 사용하는 방법이 있더라. 정말 좋아보이는데 내가 배운 date와는 달라서 검색해보니 date, Calenar class는 다양한 오류가 있어서 Java8에서부터는 더이상 피할 필요가 없도록 LocalDate와 LocalDateTime이 추가되었다고 한다.

public int solution(int age) {
        LocalDate today = LocalDate.now();
        return today.getYear() - age;
    }

LocalDate.now()를 이용해서 로컬 컴퓨터의 현재 날짜 정보를 가지고와 today에 넣고 today.getYear 년도의 값만 가지고 와서 - 나이를 빼면 몇년도에 태어났는 지 알수있다!!!


  • LocalDate : 로컬 날짜 클래스로 날짜 정보만 필요할 때 사용
// 로컬 컴퓨터의 현재 날짜 정보를 저장한 LocalDate 객체를 리턴
LocalDate currentDate = LocalDate.now();
// 파라미터로 주어진 날짜 정보를 저장한 LocalDate 객체를 리턴한다.
LocalDate targetDate = LocalDate.of(2019,11,12);
  • LocalDateTime : 날짜와 시간정보가 모두 필요할 때 사용
    (LocalTime은 시간만 필요할 때)
// 로컬 컴퓨터의 현재 날짜와 시간 정보
LocalDateTime currentDateTime = LocalDateTime.now(); 
// second,nanoSecond 매개변수는 선택사항
LocalDateTime targetDateTime = LocalDateTime.of(2019, 11, 12, 12, 32,22,3333);

공식 문서 👉 LocalDate, LocalDateTime

LocalDate는 LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. Other date fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. For example, the value "2nd October 2007" can be stored in a LocalDate.

LocalDateTime은 LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.

0개의 댓글