javascript:如何将日期字符串 (YYYY-MM-DD) 增加 1 天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5116657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:00:24  来源:igfitidea点击:

javascript: how can I increment a date string (YYYY-MM-DD) by 1 day

javascriptjquery

提问by Haroldo

I know how to do this in php with date() and mktime() functions, but have no idea how to accomplish the same thing in javascript...

我知道如何使用 date() 和 mktime() 函数在 php 中执行此操作,但不知道如何在 javascript 中完成相同的操作...

function incr_date(date_str){
    //...magic here
    return next_date_str;
}

var date_str = '2011-02-28';
console.log( incr_date(date_str) ); //want to output "2011-03-01"

is this even possible with js?

这甚至可以用 js 实现吗?

回答by T.J. Crowder

First you parse it, then you use dt.setDate(dt.getDate() + 1). You'll have to parse it manually, though, or using DateJSor similar; that format is not yet supported across all major browsers (new Date(date_str)will not workreliably cross-browser; see note below). And then convert it back to your format.

首先解析它,然后使用dt.setDate(dt.getDate() + 1). 但是,您必须手动解析它,或者使用DateJS或类似工具;所有主要浏览器尚不支持该格式(无法跨浏览器可靠地new Date(date_str)工作;请参阅下面的注释)。然后将其转换回您的格式。

Something along these lines:

沿着这些路线的东西:

function incr_date(date_str){
  var parts = date_str.split("-");
  var dt = new Date(
    parseInt(parts[0], 10),      // year
    parseInt(parts[1], 10) - 1,  // month (starts with 0)
    parseInt(parts[2], 10)       // date
  );
  dt.setDate(dt.getDate() + 1);
  parts[0] = "" + dt.getFullYear();
  parts[1] = "" + (dt.getMonth() + 1);
  if (parts[1].length < 2) {
    parts[1] = "0" + parts[1];
  }
  parts[2] = "" + dt.getDate();
  if (parts[2].length < 2) {
    parts[2] = "0" + parts[2];
  }
  return parts.join("-");
}

Live example

活生生的例子

Note that setDatewill correctly handle rolling over to the next month (and year if necessary).

请注意,这setDate将正确处理滚动到下个月(如有必要,还有一年)。

Live example

活生生的例子

The above is tested and works on IE6, IE7, IE8; Chrome, Opera, and Firefox on Linux; Chrome, Opera, Firefox, and Safari on Windows.

以上经过测试,适用于IE6、IE7、IE8;Linux 上的 Chrome、Opera 和 Firefox;Windows 上的 Chrome、Opera、Firefox 和 Safari。

A note about support for this format in JavaScript: The new Date(string)constructor in JavaScript only recently had the formats that it would accept standardized, as of ECMAScript 5th editionreleased in December 2009. Your format will be supported when browsers support it, but as of this writing, no released version of IE (not even IE8) supports it. Other recent browsers mostly do.

关于 JavaScript 支持此格式的说明:JavaScript 中的new Date(string)构造函数最近才具有可接受的标准化格式,截至 2009 年 12 月发布的ECMAScript 第 5 版。当浏览器支持时,您的格式将得到支持,但在撰写本文时, 没有发布版本的 IE(甚至不支持 IE8)支持它。其他最近的浏览器大多如此。

回答by Imrul

If you are using jQuery & jQuery UIthen use the following:

如果您使用jQuery 和 jQuery UI,请使用以下内容:

var dt = $.datepicker.parseDate('yy-mm-dd', '2011-02-25');
dt.setDate(dt.getDate() + 1)
var dtNew = $.datepicker.formatDate('yy-mm-dd', dt);

You can parseand formatany way you want, and most importantly you will not need a new function in your JS Library.

您可以任何方式解析格式化,最重要的是,您的 JS 库中不需要新函数。

回答by Andrew Wilkinson

First you need to turn your date string into a Date object.

首先,您需要将日期字符串转换为 Date 对象。

var date = new Date('2011-02-28');

Then you need to add one to the day part of the date.

然后您需要在日期的天部分添加一个。

date.setDate(d.getDate() + 1);

Although this looks it might end up with the 29th of February, it won't and will give you the 1st March.

虽然看起来它可能会在 2 月 29 日结束,但它不会并且会给你 3 月 1 日。

回答by Jonathan Herman

I modified this excellent answer https://stackoverflow.com/a/5116693/4021614to handle both incrementing and decrementing by any amount (using this method https://stackoverflow.com/a/25114400/4021614).

我修改了这个优秀的答案https://stackoverflow.com/a/5116693/4021614以处理任意数量的递增和递减(使用此方法https://stackoverflow.com/a/25114400/4021614)。

function incrementDate(date_str, incrementor) {
    var parts = date_str.split("-");
    var dt = new Date(
        parseInt(parts[0], 10),      // year
        parseInt(parts[1], 10) - 1,  // month (starts with 0)
        parseInt(parts[2], 10)       // date
    );
    dt.setTime(dt.getTime() + incrementor * 86400000);
    parts[0] = "" + dt.getFullYear();
    parts[1] = "" + (dt.getMonth() + 1);
    if (parts[1].length < 2) {
        parts[1] = "0" + parts[1];
    }
    parts[2] = "" + dt.getDate();
    if (parts[2].length < 2) {
        parts[2] = "0" + parts[2];
    }
    return parts.join("-");
};

example:

例子:

//increment by 7 days
incrementDate('2015-01-01', 7);
//returns '2015-01-08'

//decrement by 1 day
incrementDate('2015-01-01', -1);
//returns '2014-12-31'

回答by Richard Dalton

I would use date.js from here - http://www.datejs.com/

我会从这里使用 date.js - http://www.datejs.com/

Has lots of functions for handling this kind of thing.

有很多功能可以处理这种事情。

回答by Andrea

Yes. First you read the date and you convert to a date object, then you add 1 day and return the result

是的。首先读取日期并转换为日期对象,然后添加 1 天并返回结果

function incrementDate(date_str) {
    var date = new Date(date_str);
    date.setDate(date.getDate() + 1);
    return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
}

The Date object, which is native in javascript, takes care of all problems arising from leap years and so on.

javascript 原生的Date 对象负责处理闰年等引起的所有问题。

回答by Abdul

i hope this will help

我希望这个能帮上忙

function incr_date(date_str,no_of_days_to_add){
 var futureDate=new Date(date_str);

  futureDate.setDate(new Date().getDate()+no_of_days_to_add);
  var next_date_str= futureDate;

    return next_date_str;
}