[TIL] 230818

CodeBee_·2023년 8월 18일

TIL

목록 보기
3/6

날짜 비교하기

입출력 예 #1
date1이 date2보다 하루 앞서기 때문에 1을 return 합니다.
입출력 예 #2
date1과 date2는 날짜가 서로 같으므로 date1이 더 앞서는 날짜가 아닙니다. 따라서 0을 return 합니다.


✨ 내가 푼 풀이

function solution1(date1, date2) {
    
    const [year1, month1, day1] = date1;
    const [year2, month2, day2] = date2;
    
    if(year1 < year2){
        return 1;
    } else if (year1 > year2) {
        return 0;
    }else{
        if(month1 < month2){
            return 1
        }else if(month1 > month2) {
            return 0;
        }else{
            if (day1 < day2) {
                return 1;
            }else{
                return 0;
            }
        }
    }
    return 1;
}

✨ 다른 사람의 문제풀이 참고 해석

function solution2 (date1, date2) {
    
    //배열 비구조화 할당(destructuring)을 사용하여 각 값을 변수에 할당
    const [year1, month1, day1] = date1;
    const [year2, month2, day2] = date2;
    
    // 두 날짜의 연도가 다르다면, 연도가 작은 쪽을 반환
    if (year1 !== year2 ) return year1 < year2 ? 1 : 0;
    if (month1 !== month2) return month1 < month2 ? 1 : 0;
    if (day1 !== day2) return day1 < day2 ? 1 : 0;
    // 위의 모든 조건문을 통과했다면, 두 날짜는 서로 같은 날짜이므로 0을 반
    return 0;
}

solution3 방법은 시간복잡도가 오래걸리는 편이었으나 새롭고 깔끔한 방법으로 풀었길래 참고하고자 가져왔다.

const solution3 = (date1, date2) => new Date(date1) < new Date(date2) ? 1 : 0
profile
엉금엉금 공부 블로그

1개의 댓글

comment-user-thumbnail
2023년 8월 18일

매일 기록하시는게 멋져요!! 응원합니다 :)

답글 달기