본문 바로가기
개발로그/알고리즘

프로그래머스 Lv.0 날짜 비교하기

by 쩜징 2023. 7. 10.

프로그래머스 Lv.0 날짜 비교하기


정수 배열 date1과 date2가 [year, month, day] 꼴로 주어진다.

두 배열의 날짜를 비교했을 때

date1이 date2 보다 앞서는 날짜라면 return 1,

아니면 return 0을 하는 문제

 

** 풀이방법 

배열의 원소들을

문자열로 합쳐서 날짜형식으로 변환시키고,

메소드를 사용해 날짜를 비교한다.


- java.time패키지의 LocalDate 클래스를 사용해 날짜 형식으로 변환

 static LocalDate of (int year, int month, int dayOfMonth) 

 

LocalDate localDate1 = LocalDate.of(date1[0],date1[1],date1[2]);
LocalDate localDate2 = LocalDate.of(date2[0],date2[1],date2[2]);

 

- isBefore()메서드를 사용해 이전 날짜인지 비교

 boolean isAfter(ChronoLocalDate other)   //주어진 날짜가 매개변수 날짜의 이후 날짜인지 비교

 boolean isBefore(ChronoLocalDtae other)  //주어진 날짜가 매개변수 날짜의 이전 날짜인지 비교

 boolean isEqual(ChronoLocalDate other)  //주어진 날짜가 매개변수 날짜와 같은지 비교

 

if (localDate1.isBefore(localDate2))
            answer=1;

 

<> 전체코드 </> 

import java.time.LocalDate;
class Solution {
    public int solution(int[] date1, int[] date2) {
        int answer = 0;
        
        //날짜로 변환
        LocalDate localDate1 = LocalDate.of(date1[0],date1[1],date1[2]);
        LocalDate localDate2 = LocalDate.of(date2[0],date2[1],date2[2]);
        
        //날짜 비교
        if (localDate1.isBefore(localDate2))
            answer=1;
        return answer;
    }
}

반응형

댓글