자바스크립트 – 날짜 계산하기

날짜 관련 함수가 많이 필요한데, 이것도 참…아래 그림처럼 많은 옵션이 있을 수 있다.

한주뒤, 한주전,

한달뒤, 한달전

이번달, 올해 첫날 등등등 계산한 코드 일단 적어둠. 저장용

![](assets/images/2023/03/image-2.png?resize=980%2C207&ssl=1)
function search_date_to_str(future) {
    return future.getFullYear() + '-' + ((future.getMonth() + 1) < 10 ? '0' : '') + (future.getMonth() + 1) + '-' + (future.getDate() < 10 ? '0' : '') + future.getDate();
}

    var today = new Date(); // get today date
    // var today = new Date('2022/12/27/18:30');
    var today_string = search_date_to_str(today);
    var y = today.getFullYear();
    var m = today.getMonth();
    var thismonth_start_string = search_date_to_str(new Date(y, m, 1));
    var thismonth_end_string = search_date_to_str(new Date(y, m + 1, 0));
    var thisyear_string = search_date_to_str(new Date(y, 0, 1));

    var nextweek = new Date()
    nextweek.setDate(nextweek.getDate() + 7)
    var nextweek_string = search_date_to_str(nextweek);
    var prevweek = new Date()
    prevweek.setDate(prevweek.getDate() - 7)
    var prevweek_string = search_date_to_str(prevweek);
    var future = new Date();
    future.setMonth(future.getMonth() - 1);
    y = future.getFullYear();
    m = future.getMonth();
    var prevmonth_start_string = search_date_to_str(new Date(y, m, 1));
    var prevmonth_end_string = search_date_to_str(new Date(y, m + 1, 0));
    var future1 = new Date();
    future1.setMonth(future1.getMonth() + 1);
    y = future1.getFullYear();
    m = future1.getMonth();
    var nextmonth_start_string = search_date_to_str(new Date(y, m, 1));
    var nextmonth_end_string = search_date_to_str(new Date(y, m + 1, 0));

참고 페이지

[JS] 📚 자바스크립트 Date 메소드 💯 총정리

Share: Twitter Facebook
Bongjun Hur's Picture

About Bongjun Hur

BJ is a dev.

Seoul, Korea https://devbj.com