text/JavaScript

날짜 계산 [날짜 간 차이, 주(week) 계산, 날짜 더하기 빼기]

hoonzii 2023. 3. 24. 23:45
반응형

주먹구구 js 코딩~

할 때마다 찾아보는 듯해서 어딘가 정리해 놓기... (아마 점점 추가하지 않을까...?)

 

날짜 객체 생성

const date = new Date();

 

 

날짜에 상수 더하기 빼기

let date = new Date("2023-03-14");
console.log(date); // 2023-03-14T00:00:00.000Z

let plus_day = new Date(date.setDate(date.getDate() + 1));
console.log(plus_day); //2023-03-15T00:00:00.000Z

let minus_day = new Date(date.setDate(date.getDate() - 2));
console.log(minus_day); //2023-03-13T00:00:00.000Z

 

날짜간의 일 수 차이 계산을 위함 함수

function dateDiff(start_date, end_date) {
    let dateDiff =
    (new Date(end_date).getTime() - new Date(start_date).getTime())
    / (1000 * 60 * 60 * 24);
    return dateDiff;
}

 

특정 날짜의 월별 주차수 구하기 위한 함수

const getWeek = (date) => {
    const currentDate = date.getDate();
    const firstDay = new Date(date.setDate(1)).getDay();

    return Math.ceil((currentDate + firstDay) / 7);
};

 

특정 날짜의 연도별 주차수를 구하기 위한 함수

const getYearWeek = (date) => {
    const onejan = new Date(date.getFullYear(),0,1);
    return Math.ceil((((date - onejan) / 86400000) + onejan.getDay()+1)/7);
};

console.log(getYearWeek(new Date("2023-03-14")));

//11

 

특정 날짜가 들어왔을때 해당 날짜가 속한 주차의 월요일,  일요일 날짜 반환 함수

function getWeekendRange(date) {
    let start_date = null; // 월요일
    let end_date = null; // 일요일
    
    let current_date = date;
    if(typeof current_date == "string"){
        current_date = new Date(current_date);
    }

    let dateNumber = current_date.getDay(); //[1,2,3,4,5,6,0]
    start_date = current_date.setDate(current_date.getDate() - dateNumber);
    if(dateNumber == 0) { start_date = current_date.setDate(current_date.getDate() - 7);}
    end_date = current_date.setDate(current_date.getDate() + (7-dateNumber));
    
    return {"start_date" : new Date(start_date), "end_date" : new Date(end_date) };
}

console.log(getWeekendRange("2023-03-14"));

/*
{
  start_date: 2023-03-12T00:00:00.000Z,
  end_date: 2023-03-17T00:00:00.000Z
}
*/

 

반응형