加入JavaScript天(S)(JavaScript add day(s))

2019-06-26 15:29发布

如何每天(或2天)添加到日期31.07.2012和格式DD.MM.YYYY(相同的格式输入日期)返回结果?

Answer 1:

    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);
    }


Answer 2:

最好的办法是使用JavaScript日期对象。 的日期对象在javascirpt被初始化为毫米/日/年或日期(年,月-1,日期)。 那是,

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())

月1日期(年,月-1,日期)使用,因为个月从0开始

其结果将是

"02.08.2012"


Answer 3:

/**
 * 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());


Answer 4:

假设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;
};


Answer 5:

这会为你做它

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()));


文章来源: JavaScript add day(s)