Javascript 向日期字符串添加 1 或 2 天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7013738/
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-08-24 00:15:30  来源:igfitidea点击:

Adding 1 or 2 days to a date string

javascriptdate

提问by Lee

I have got a string which is maybe date = "10/08/2011";English time style.

我有一个可能是date = "10/08/2011";英国时间风格的字符串。

Its a plain string, so I need to be able to add 1 or 2 days to it.

它是一个普通的字符串,所以我需要能够添加 1 或 2 天。

I have tried a few things but can't work it out as I am normally a PHP guy not JavaScript.

我已经尝试了一些东西,但无法解决,因为我通常是一个 PHP 人而不是 JavaScript。

Any help is greatly appreciated.

任何帮助是极大的赞赏。

Thanks

谢谢

Lee

UPDATE

更新

Why does this seem to be so hard, i've been stuck on this for an hour now..... I want to give the code a plain string which is mm/dd/yyyy - 10/08/2011 and i want back something like 11/08/2011

为什么这看起来这么难,我已经坚持了一个小时......我想给代码一个简单的字符串,它是 mm/dd/yyyy - 10/08/2011 我想要回到 11/08/2011 之类的东西

Why so hard ?? this is why i hate javascript and prefer PHP :-(

为什么这么难??这就是为什么我讨厌 javascript 而更喜欢 PHP :-(

回答by KooiInc

It's not all that complex:

并不是那么复杂:

//convert string to date
var dattmp = "10/08/2011".split('/').reverse().join('/');
var nwdate =  new Date(dattmp);

// to add 1 day use:
nwdate.setDate(nwdate.getDate()+1);

//to retrieve the new date use
[nwdate.getDate(),nwdate.getMonth()+1,nwdate.getFullYear()].join('/');

//all in one:
function dateAddDays( /*string dd/mm/yyyy*/ datstr, /*int*/ ndays){
  var dattmp = datstr.split('/').reverse().join('/');
  var nwdate =  new Date(dattmp);
  nwdate.setDate(nwdate.getDate() + (ndays || 1));
  return [ zeroPad(nwdate.getDate(), 10)
          ,zeroPad(nwdate.getMonth()+1, 10)
          ,nwdate.getFullYear() ].join('/');
}

//function to add zero to date/month < 10
function zeroPad(nr, base){
  var len = (String(base).length - String(nr).length) + 1;
  return len > 0? new Array(len).join('0') + nr : nr;
}

//examples
console.log(dateAddDays("10/08/2011"));     //=> 11/08/2011
console.log(dateAddDays("10/08/2011", -5)); //=> 05/08/2011

if you really want it simple - without using the Date Object:

如果你真的想要简单 - 不使用日期对象:

var datePlus1 = '10/08/2011'.split('/');
datePlus1[0] = Number(datePlus1[0])+1;
console.log(datePlus1.join('/')); //=> 11/08/2011

Here'sa small datetime handling object which may be of use.

这是一个可能有用的小型日期时间处理对象。

回答by Mike C

To add 2 days:

添加 2 天:

var theDate = new Date("10/28/2011");
theDate.setDate(theDate.getDate()+2);

回答by GNi33

You will need to convert the String into a Date-Object. With this you can call the .getDate() and setDate() - Functions to modify the date.

您需要将字符串转换为日期对象。有了这个,您可以调用 .getDate() 和 setDate() - 函数来修改日期。

But to achieve this, the date has to be in one of the following formats:

但要实现这一点,日期必须采用以下格式之一:

  1. MM/dd/yyyy
  2. yyyy/MM/dd
  3. MM-dd-yyyy
  4. MMMM dd, yyyy
  5. MMM dd, yyyy
  1. 月/日/年
  2. 年年/月/日
  3. MM-dd-yyyy
  4. MMMM dd, yyyy
  5. MMM dd, yyyy

So, maybe you would have to switch day and month in your string before converting, as I'm not sure if Month or Day is your first number.

因此,也许您必须在转换之前在字符串中切换日期和月份,因为我不确定 Month 或 Day 是您的第一个数字。

For european Dates, you could change the string into the right format with something like this:

对于欧洲日期,您可以将字符串更改为正确的格式,如下所示:

var date = "10/08/2011";
var eurDate = date.substr(3,2) + "/" + date.substr(0,2) + "/" + date.substr(6);

Links that could help you with this:

可以帮助您解决此问题的链接:

http://programming.top54u.com/post/Javascript-Convert-String-to-Date.aspx

http://programming.top54u.com/post/Javascript-Convert-String-to-Date.aspx

http://www.adp-gmbh.ch/web/js/date/add_days.html

http://www.adp-gmbh.ch/web/js/date/add_days.html

edit:

编辑:

JSFiddle with an example: http://jsfiddle.net/4W8yM/11/

JSFiddle 举个例子:http: //jsfiddle.net/4W8yM/11/

回答by ShankarSangoli

Try this

尝试这个

var date =  new Date("10/08/2011");

date = new Date(date.setDate(date.getDate()+1));//1 represents 1 day to add so you specify as per your need

var dateStr = date.getDay() + '/' + (date.getMonth() + 1) + '/' + date.getUTCFullYear();

回答by kennebec

You must enforce a string to be interpreted as date-month-year or or month-date-year, or it will depend on the user's settings.

您必须强制将字符串解释为日期-月-年或月-日-年,否则将取决于用户的设置。

You can assemble the date from the string to ensure the date-month format:

您可以从字符串中组合日期以确保日期-月份格式:

Date.fromDM=function(string){
    var A= string.match(/([1-9]\d*)/g);
    if(A.length!== 3) throw 'bad date'; 
    return new Date(A[2]*1, A[1]-1, A[0]*1);
}
Date.fromMD=function(string){
    var A= string.match(/([1-9]\d*)/g);
    if(A.length!== 3) throw 'bad date'; 
    return new Date(A[2]*1, A[0]-1, A[1]*1);
}



/*  Date.fromDM('10,08,2011')
return value: (Date)
Wed Aug 10 2011 00:00:00 GMT-0400 (Eastern Daylight Time)
*/

/*Date.fromMD('10,08,2011')
return value: (Date)
Sat Oct 08 2011 00:00:00 GMT-0400 (Eastern Daylight Time)
*/

回答by Arnold

I tried this and got the result.

我试过这个并得到了结果。

var dat = new Date('2018-03-16');

//use toISOString() to get the string value 2018-03-16T16:38:00.000Z
//substring(0,10) gets 2018-03-16
//reverse to gets 16-03-2018
var ret = dat.toISOString().substring(0, 10).split('-').reverse()

//rearranging to whatever format you want
var t = ret[0];
ret[0] = ret[1];
ret[1] = t;

//result
console.log(ret.join('/'))