Subtract days, months, years from a date in JavaScript

前端 未结 8 591
慢半拍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:53

    Use the moment.js library for time and date management.

    import moment = require('moment');
    
    const now = moment();
    
    now.subtract(7, 'seconds'); // 7 seconds ago
    now.subtract(7, 'days');    // 7 days and 7 seconds ago
    now.subtract(7, 'months');  // 7 months, 7 days and 7 seconds ago
    now.subtract(7, 'years');   // 7 years, 7 months, 7 days and 7 seconds ago
    // because `now` has been mutated, it no longer represents the current time
    

提交回复
热议问题