js 获取日期小记

获取当前时间在页面展示中是常见的,最近很早之前写的一个获取当前时间的函数出现了bug,导致时间戳传递失败,数据请求失败。

function getNowFormatDate() {
    var date = new Date();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + month + strDate;
    return currentdate;
}

简单来看对个位数月和日也做了处理了,但是当月大于9的时候就会发现时间错乱,比如,2019年10月9号的话,返回的世界是2038,这是为什么呢?

    var date = new Date();
    var month = date.getMonth() + 1;
    console.log(month);
    console.log(typeof (month));

我们发现原来date的get函数返回的是数字,2019+10+9=2038,对于个位数的时间,函数添加了字符串 “0”这样就把number类型强转成了string类型,所以是字符串的拼接。

其实我们可以从源码中看到 确实 return的是number类型。

总结:

自测一定要全面,在一些基础函数的使用上,不能想当然的认为,要认真实践。另外,源码真是万物之母,有必要留个心开始对着方面做些积累了。

发布了29 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/bjhan_csdn/article/details/102455022