我有一个字符串,可能是date = "10/08/2011";英国时间风格.
它是一个普通的字符串,所以我需要能够添加1或2天.
我尝试了一些但无法解决的问题,因为我通常是一个不是JavaScript的PHP人.
任何帮助是极大的赞赏.
谢谢
背风处
UPDATE
为什么这看起来如此困难,我现在已经坚持了一个小时.....我想给代码一个简单的字符串,这是mm/dd/yyyy - 10/08/2011我想要回来像11/08/2011
为什么这么难?这就是为什么我讨厌javascript而不喜欢PHP :-(
Koo*_*Inc 14
它不是那么复杂:
//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
Run Code Online (Sandbox Code Playgroud)
如果你真的想要它简单 - 不使用Date对象:
var datePlus1 = '10/08/2011'.split('/');
datePlus1[0] = Number(datePlus1[0])+1;
console.log(datePlus1.join('/')); //=> 11/08/2011
Run Code Online (Sandbox Code Playgroud)
这是一个可能有用的小日期处理对象.
要添加2天:
var theDate = new Date("10/28/2011");
theDate.setDate(theDate.getDate()+2);
Run Code Online (Sandbox Code Playgroud)