JavaScript add day(s)

2020-03-31 04:45发布

How to add a day (or 2 days) to date 31.07.2012 and return result in format dd.MM.yyyy (same format as input date)?

5条回答
forever°为你锁心
2楼-- · 2020-03-31 04:52

This will do it for you

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()));
查看更多
Anthone
3楼-- · 2020-03-31 04:55
/**
 * 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());
查看更多
霸刀☆藐视天下
4楼-- · 2020-03-31 05:00
    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);
    }
查看更多
我命由我不由天
5楼-- · 2020-03-31 05:01

assuming inputDateString format is 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;
};
查看更多
Anthone
6楼-- · 2020-03-31 05:07

The best way would be to use the javascript date object. The date object in javascirpt is initialized as mm/dd/yyyy or as Date(year,month-1, date). That is,

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 is used in Date(year,month-1, date) because months start with 0

The result will be

"02.08.2012"
查看更多
登录 后发表回答