>  Q&A  >  본문

javascript - 日期格式错误为NaN-NaN-NaN 请问如何解决

现在好多表的日期格式是:2015-11-4 12:19:52 使用的是这段JS

function getLocalTime(value, row, index) {
    var a = new Date(value);
    return formatDate(a);
}

function formatDate(now) {
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var date = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    return year + "-" + month + "-" + date;
}

但是今天有张表从数据库中获取到的日期,却显示为NaN-NaN-NaN.
网上问了好多度娘,都没有个正确可行的办法来解决,请问这里的大神,有什么方法可以让我的日期重新回归这个格式:2015-11-4 12:19:52

黄舟黄舟2750일 전1315

모든 응답(2)나는 대답할 것이다

  • ringa_lee

    ringa_lee2017-04-10 16:10:44

    NaN是Not A Number的意思,你的value看起来是传入了一个字符串,并且不是一个有效的日期字符串

    产生这个问题的原因是Date构造函数接受的若干种参数中,如果你传入的是String,会被当成是一个Date.parse方法可以接受处理的符合RFC 2822标准的时间字符串来处理,所以时间戳是不行的

    详见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

    如果只是简单修改,考虑改成这样吧:

    function getLocalTime(value) { //row, index两个参数我看毫无作用??
        var a = parseInt(value);
        return isNaN(a) ? "非法日期" : formatDate(new Date(a));
    }
    
    function formatDate(now) {
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        return year + "-" + month + "-" + date;
    }

    회신하다
    0
  • 怪我咯

    怪我咯2017-04-10 16:10:44

    楼下的大神的方法也可以,不过我找到更好的方法了。
    之所以会造成显示错误,是因为,我传的value,没有值。
    var a = new Date(value);
    这个value实际上是我要让显示的字段为返回时间的日期,这个返回时间的字段是backTime,只要获取到这个值就会正常显示了。
    最后解决的代码显示为:
    function getLocalTime(value, row, index) {

                    var a = new Date(row.backTime);
                    return formatDate(a);
                }
            //时间格式
            function formatDate(now) {
                var year = now.getFullYear();
                var month = now.getMonth() + 1;
                var date = now.getDate();
                var hour = now.getHours();
                var minute = now.getMinutes();
                var second = now.getSeconds();
                return year + "-" + month + "-" + date;
            }
    

    회신하다
    0
  • 취소회신하다