如何在日期 31.07.2012 中添加一天(或 2 天)并以 dd.MM.yyyy 格式返回结果(与输入日期格式相同)?
问问题
1427 次
5 回答
3
最好的方法是使用 javascript 日期对象。javascirpt 中的日期对象被初始化为 mm/dd/yyyy 或 Date(year,month-1, date)。那是,
dateString = "31.07.2012"
dateSplit = dateString.split('.')
date = new Date(dateSplit[2], dateSplit[1]-1, dateSplit[0])
date.setDate(date.getDate()+2)
newDateString = ((date.getDate() > 10) ? date.getDate() : ("0" + date.getDate())) + "." + ((date.getMonth()+1 > 10) ? date.getMonth()+1 : ("0" + (date.getMonth()+1))) + "." + (date.getFullYear())
month-1 用于 Date(year,month-1, date) 因为月份以 0 开头
结果将是
"02.08.2012"
于 2012-07-31T07:29:43.410 回答
2
/**
* Format date (2012.08.31)
*/
Date.prototype.format = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '.' + (mm[1]?mm:"0"+mm[0]) + '.' + (dd[1]?dd:"0"+dd[0]); // padding
}
/**
* Increase current time
*/
Date.prototype.increase_days = function(days) {
this.setTime(this.getTime() + (days * (1000 * 60 * 60 * 24)));
return this;
}
//usage:
var date = new Date();
date.increase_days(2);
console.log(date.format());
于 2012-07-31T07:19:06.470 回答
2
var numDaysToAdd = 2;
var inputDateString = "31.07.2012";
var resultDate = stringToDate(inputDateString);
resultDate.setDate( resultDate.getDate()+numDaysToAdd );
var result = dateToString( resultDate );
alert(result);
function stringToDate( aString )
{
var dateArray = aString.split(".");
return new Date(dateArray[2],dateArray[1]-1,dateArray[0]);
}
function dateToString( aDate )
{
var date = aDate.getDate();
date = (date > 9) ? date : "0"+date.toString();
var month = aDate.getMonth()+1;
month = (month > 9) ? month : "0"+month.toString();
var year = aDate.getFullYear();
return (date+"."+month+"."+year);
}
于 2012-07-31T07:40:03.543 回答
1
假设inputDateString
格式是dd.mm.yyyy
function addDaysToDate (inputDateString ,noOfDays ){
var myDate=dateString.split(".");
var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
var dateInMilliSec = new Date(newDate).getTime();
var addDaysToTime = new Date(dateInMilliSec + (86400000 * noOfDays));
var dd = addDaysToTime.getDate();
var MM = addDaysToTime.getMonth()+1;
var yyyy = addDaysToTime.getFullYear();
return dd+"."+MM+"."+yyyy;
};
于 2014-12-15T09:40:49.163 回答
0
这将为您完成
var d = "31.07.2012";
d = d.split(".");
date = new Date(d[2],d[1]-1,d[0]);
date.setDate(date.getDate() + 2);
document.body.innerHTML += (date.getDate() + "." + date.getMonth() + "." + (date.getFullYear()));
于 2012-07-31T07:33:33.067 回答