Subtract days, months, years from a date in JavaScript

前端 未结 8 587
慢半拍i
慢半拍i 2020-12-13 03:32

Does anybody know of a simple way of taking a date (e.g. Today) and going back X days, X months and X years?

I have tried that:

var date = new Date()         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 03:57

    I have a simpler answer, which works perfectly for days; for months, it's +-2 days:

    let today=new Date();
    const days_to_subtract=30;
    let new_date= new Date(today.valueOf()-(days_to_subtract*24*60*60*1000));
    

    You get the idea - for months, multiply by 30; but that will be +-2 days.

提交回复
热议问题