JS日期对象通过套接字转换为字符串

JS date object converted to string via socket?

本文关键字:转换 字符串 套接字 日期 对象 JS      更新时间:2023-09-26

显然,我作为消息块的一部分创建的日期对象在通过套接字后自动转换为字符串。也就是这个代码:

    $('form').submit(function() {
        var now = new Date();
        var msgObj = {
            'now' : now,
            'text' : "hello"
        };
        console.log(msgObj);
        socket.emit('message', msgObj);
        $('#m').val('');
        return false;
    });
    socket.on('chat message', function(msgObj) {
        console.log(msgObj);
        var now = msgObj.now,
            h = now.getHours(),
            m = now.getMinutes();
        console.log(h+':'+m);
    });

将以下输出输出到控制台:

Object {now: Thu Jun 12 2014 20:49:35 GMT+0100 (BST), text: "hello"}
Object {now: "2014-06-12T19:49:35.258Z", text: "hello"}

所以date对象变成了一个中间的字符串。最后的控制台日志失败,因为string显然没有getHours()方法。为什么这个值会改变?处理广播的代码不显眼:

//...
socket.on('message', function(msgObj) {
    io.emit('message', msgObj);
});

try this…

socket.on('chat message', function(msgObj) {
        console.log(msgObj);
        var now = new Date(msgObj.now),
            h = now.getHours(),
            m = now.getMinutes();
        console.log(h+':'+m);
    });