js在使用时要对日期的进行加减天数操作,但是操作出来的日期格式和原来不一样


正常加一天日期输出日期格式是 yyyy-m-d

function moreDate(date1,i) {
    let date =new Date(date1)
    let year = date.getFullYear();
    let month = date.getMonth()+1;
    let day = date.getDate()+i;
    return year+"-"+month+"-"+day
}

输出结果





修改后的代码,使用padStart是为数值补全指定位数,格式就为 yyyy-mm-dd

function moreDate(date1,i) {
    let date =new Date(date1)
    let year = date.getFullYear();
    //补全位数
    let month = (date.getMonth()+1).toString().padStart(2,'0');;
    let day = (date.getDate()+i).toString().padStart(2,'0');;
    return year+"-"+month+"-"+day
}
修改之后

————————————————————————

最近使用的时候发现bug了再更改一下

原来的方法在减日期时,例如10月01日减一天会变成10月00日,再获取日期时就变成NaN了

更改后的,先对日期进行加减操作再获取日期

        function moreDate(date1,i) {
            let date =new Date(date1)
             date.setDate(date.getDate()+i)
            let year = date.getFullYear();
            //补全位数
            let month = (date.getMonth() + 1).toString().padStart(2, '0')
            let day = (date.getDate()).toString().padStart(2, '0')
            return year+"-"+month+"-"+day
        }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐