首页 文章

从JavaScript中减去日期

提问于
浏览
439

有人知道一个简单的约会方式(例如今天)和回去X天吗?

因此,例如,如果我想在今天前5天计算日期 .

30 回答

  • 46

    尝试这样的事情:

    var d = new Date();
     d.setDate(d.getDate()-5);
    

    请注意,这会修改日期对象并返回更新日期的时间值 .

    var d = new Date();
    
    document.write('Today is: ' + d.toLocaleString());
    
    d.setDate(d.getDate() - 5);
    
    document.write('<br>5 days ago was: ' + d.toLocaleString());
    
  • 9
    var dateOffset = (24*60*60*1000) * 5; //5 days
    var myDate = new Date();
    myDate.setTime(myDate.getTime() - dateOffset);
    

    如果您在整个Web应用程序中执行大量日常操作,DateJS将使您的生活更轻松:

    http://simonwillison.net/2007/Dec/3/datejs/

  • 19

    它是这样的:

    var d = new Date(); // today!
    var x = 5; // go back 5 days!
    d.setDate(d.getDate() - x);
    
  • -4

    我注意到getDays X在日/月边界上不起作用 . 只要您的日期不是在1970年之前,就可以使用getTime .

    var todayDate = new Date(), weekDate = new Date();
    weekDate.setTime(todayDate.getTime()-(7*24*3600000));
    
  • -2

    我为Date制作了这个原型,以便我可以传递负值来减去天数和正值来增加天数 .

    if(!Date.prototype.adjustDate){
        Date.prototype.adjustDate = function(days){
            var date;
    
            days = days || 0;
    
            if(days === 0){
                date = new Date( this.getTime() );
            } else if(days > 0) {
                date = new Date( this.getTime() );
    
                date.setDate(date.getDate() + days);
            } else {
                date = new Date(
                    this.getFullYear(),
                    this.getMonth(),
                    this.getDate() - Math.abs(days),
                    this.getHours(),
                    this.getMinutes(),
                    this.getSeconds(),
                    this.getMilliseconds()
                );
            }
    
            this.setTime(date.getTime());
    
            return this;
        };
    }
    

    所以,要使用它,我可以简单地写:

    var date_subtract = new Date().adjustDate(-4),
        date_add = new Date().adjustDate(4);
    
  • 1

    得到moment.js . 所有酷孩子都使用它 . 它有更多的格式选项,等等

    var n = 5;
    var dateMnsFive = moment(<your date>).subtract(n , 'day');
    

    可选的!转换为JS Date obj进行Angular绑定 .

    var date = new Date(dateMnsFive.toISOString());
    

    可选的!格式

    var date = dateMnsFive.format("YYYY-MM-DD");
    
  • 1

    将日期拆分为多个部分,然后返回带有调整值的新日期

    function DateAdd(date, type, amount){
        var y = date.getFullYear(),
            m = date.getMonth(),
            d = date.getDate();
        if(type === 'y'){
            y += amount;
        };
        if(type === 'm'){
            m += amount;
        };
        if(type === 'd'){
            d += amount;
        };
        return new Date(y, m, d);
    }
    

    请记住,月份是零,但日子不是 . 即新日期(2009年,1,1)= 2009年2月1日,新日期(2009年,1,0)== 2009年1月31日;

  • 9

    一些现有的解决方案很接近,但并不完全是我想要的 . 此函数适用于正值或负值,并处理边界情况 .

    function addDays(date, days) {
        return new Date(
            date.getFullYear(),
            date.getMonth(),
            date.getDate() + days,
            date.getHours(),
            date.getMinutes(),
            date.getSeconds(),
            date.getMilliseconds()
        );
    }
    
  • 12

    我喜欢在几毫秒内完成数学运算 . 所以使用 Date.now()

    var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds
    

    如果你喜欢它格式化

    new Date(newDate).toString(); // or .toUTCString or .toISOString ...
    

    注意: Date.now() 在旧版浏览器中不起作用(例如IE8) . Polyfill here .

    更新2015年6月

    @socketpair指出我的邋..正如他/她所说:“一年中有一天有23个小时,而有些25个由于时区规则” .

    为了扩展这一点,如果你想在5天前计算一个时区的日期变化,那么上面的答案会有一些日常的不准确之处

    • 假设(错误地) Date.now() 现在给你当前的LOCAL,或者

    • 使用 .toString() 返回本地日期,因此与UTC中的 Date.now() 基准日期不兼容 .

    但是,如果您使用UTC进行数学运算,则可以正常工作,例如

    A.你想要从5天前开始的UTC日期(UTC)

    var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds UTC
    new Date(newDate).toUTCString(); // or .toISOString(), BUT NOT toString
    

    B.您使用 Date.UTC() 以"now"以外的UTC基准日期开始

    newDate = new Date(Date.UTC(2015, 3, 1)).getTime() + -5*24*3600000;
    new Date(newDate).toUTCString(); // or .toISOString BUT NOT toString
    
  • 0

    我发现getDate()/ setDate()方法的一个问题是它太容易把所有东西都变成毫秒,而且语法有时很难让我遵循 .

    相反,我喜欢解决1天= 86,400,000毫秒的事实 .

    所以,对于你的特定问题:

    today = new Date()
    days = 86400000 //number of milliseconds in a day
    fiveDaysAgo = new Date(today - (5*days))
    

    奇迹般有效 .

    我一直使用这种方法进行30/60/365天的滚动计算 .

    您可以轻松地推断这个以创建数月,数年等的时间单位 .

  • 684
    function addDays (date, daysToAdd) {
      var _24HoursInMilliseconds = 86400000;
      return new Date(date.getTime() + daysToAdd * _24HoursInMilliseconds);
    };
    
    var now = new Date();
    
    var yesterday = addDays(now, - 1);
    
    var tomorrow = addDays(now, 1);
    
  • 0

    使用MomentJS .

    function getXDaysBeforeDate(referenceDate, x) {
      return moment(referenceDate).subtract(x , 'day').format('MMMM Do YYYY, h:mm:ss a');
    }
    
    var yourDate = new Date(); // let's say today
    var valueOfX = 7; // let's say 7 days before
    
    console.log(getXDaysBeforeDate(yourDate, valueOfX));
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
    
  • 0

    最佳答案导致我的代码中的错误,在本月的第一天,它将设置当月的未来日期 . 这是我做的,

    curDate = new Date(); // Took current date as an example
    prvDate = new Date(0); // Date set to epoch 0
    prvDate.setUTCMilliseconds((curDate - (5 * 24 * 60 * 60 * 1000))); //Set epoch time
    
  • 0

    管理日期的简单方法是使用Moment.js

    你可以使用 add . 例

    var startdate = "20.03.2014";
    var new_date = moment(startdate, "DD.MM.YYYY");
    new_date.add(5, 'days'); //Add 5 days to start date
    alert(new_date);
    

    文件http://momentjs.com/docs/#/manipulating/add/

  • 1

    如果不使用第二个变量,您可以用后x天替换7 for

    设d =新日期(新日期() . getTime() - (7 * 24 * 60 * 60 * 1000))

  • 5

    对我来说,所有组合都可以正常使用下面的代码snipplet,代码片段用于Angular-2实现,如果你需要添加天数,则传递正数numberofDays,如果你需要减去传递负数numberofDays

    function addSubstractDays(date: Date, numberofDays: number): Date {
    let d = new Date(date);
    return new Date(
        d.getFullYear(),
        d.getMonth(),
        (d.getDate() + numberofDays)
    );
    }
    
  • 2

    我得到了很好的里程数.js:

    http://www.datejs.com/

    d = new Date();
    d.add(-10).days();  // subtract 10 days
    

    太好了!

    网站包括这个美丽:

    Datejs不只是解析字符串,它将它们完全切成两半

  • 10

    如果您想要以人类可读的格式减去天数并格式化日期,则应考虑创建一个如下所示的自定义 DateHelper 对象:

    var DateHelper = {
        addDays : function(aDate, numberOfDays) {
            aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
            return aDate;                                  // Return the date
        },
        format : function format(date) {
            return [
               ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes
               ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes
               date.getFullYear()                          // Get full year
            ].join('/');                                   // Glue the pieces together
        }
    }
    
    // With this helper, you can now just use one line of readable code to :
    // ---------------------------------------------------------------------
    // 1. Get the current date
    // 2. Subtract 5 days
    // 3. Format it
    // 4. Output it
    // ---------------------------------------------------------------------
    document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -5));
    

    (另见this Fiddle

  • 1

    我已经创建了一个日期操作功能 . 您可以添加或减去任意天数,小时数,分钟数 .

    function dateManipulation(date, days, hrs, mins, operator) {
       date = new Date(date);
       if (operator == "-") {
          var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
          var newDate = new Date(date.getTime() - durationInMs);
       } else {
          var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
          var newDate = new Date(date.getTime() + durationInMs);
       }
       return newDate;
     }
    

    现在,通过传递参数来调用此函数 . 例如,这是一个函数调用,用于从今天起3天之前获取日期 .

    var today = new Date();
    var newDate = dateManipulation(today, 3, 0, 0, "-");
    
  • 0

    设置日期时,日期会转换为毫秒,因此您需要将其转换回日期:

    这种方法也考虑到了新年的变化等 .

    function addDays( date, days ) {
        var dateInMs = date.setDate(date.getDate() - days);
        return new Date(dateInMs);
    }
    
    var date_from = new Date();
    var date_to = addDays( new Date(), parseInt(days) );
    
  • 0

    你可以使用Javascript .

    var CurrDate = new Date(); // Current Date
    var numberOfDays = 5;
    var days = CurrDate.setDate(CurrDate.getDate() + numberOfDays);
    alert(days); // It will print 5 days before today
    

    对于PHP,

    $date =  date('Y-m-d', strtotime("-5 days")); // it shows 5 days before today.
    echo $date;
    

    希望它会对你有所帮助 .

  • 3
    var d = new Date();
    
    document.write('Today is: ' + d.toLocaleString());
    
    d.setDate(d.getDate() - 31);
    
    document.write('<br>5 days ago was: ' + d.toLocaleString());
    
  • 58

    我喜欢以下因为它是一行 . DST更改并不完美,但通常足以满足我的需求 .

    var fiveDaysAgo = new Date(new Date() - (1000*60*60*24*5));
    
  • 0
    var d = new Date();
    
    document.write('Today is: ' + d.toLocaleString());
    
    d.setDate(d.getDate() - 100);
    
    document.write('<br>100 days ago was: ' + d.toLocaleString());
    
  • 0

    我转换成毫秒并扣除其他月份和年份不会改变和合乎逻辑

    var numberOfDays = 10;//number of days need to deducted or added
    var date = "01-01-2018"// date need to change
    var dt = new Date(parseInt(date.substring(6), 10),        // Year
                  parseInt(date.substring(3,5), 10) - 1, // Month (0-11)
                  parseInt(date.substring(0,2), 10));
    var new_dt = dt.setMilliseconds(dt.getMilliseconds() - numberOfDays*24*60*60*1000);
    new_dt = new Date(new_dt);
    var changed_date = new_dt.getDate()+"-"+(new_dt.getMonth()+1)+"-"+new_dt.getFullYear();
    

    希望帮助

  • 0
    var date = new Date();
    var day = date.getDate();
    var mnth = date.getMonth() + 1;
    
    var fDate = day + '/' + mnth + '/' + date.getFullYear();
    document.write('Today is: ' + fDate);
    var subDate = date.setDate(date.getDate() - 1);
    var todate = new Date(subDate);
    var today = todate.getDate();
    var tomnth = todate.getMonth() + 1;
    var endDate = today + '/' + tomnth + '/' + todate.getFullYear();
    document.write('<br>1 days ago was: ' + endDate );
    
  • 1
    var today = new Date();
    var tmpDate = new Date();
    var i = -3; var dateArray = [];
    while( i < 4 ){
        tmpDate = tmpDate.setDate(today.getDate() + i);
      tmpDate = new Date( tmpDate );
      var dateString = ( '0' + ( tmpDate.getMonth() + 1 ) ).slice(-2) + '-' + ( '0' + tmpDate.getDate()).slice(-2) + '-' + tmpDate.getFullYear();
        dateArray.push( dateString );
        i++;
    }
    console.log( dateArray );
    
  • 1

    使用现代JavaScript函数语法

    const getDaysPastDate = (daysBefore, date = new Date) => new Date(date - (1000 * 60 * 60 * 24 * daysBefore));
    
    console.log(getDaysPastDate(1)); // yesterday
    
  • 1
    var daysToSubtract = 3;
    $.datepicker.formatDate('yy/mm/dd', new Date() - daysToSubtract) ;
    
  • 9
    var my date = new Date().toISOString().substring(0, 10);
    

    它只能给你2014-06-20这样的日期 . 希望会有所帮助

相关问题