JavaScript 添加天数

2022-01-15 00:00:00 format date add javascript

如何在日期 31.07.2012 中添加一天(或 2 天)并以 dd.MM.yyyy 格式(与输入日期格式相同)返回结果?

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

推荐答案

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

相关文章