我的节点聊天应用程序在客户端没有显示正确的时间,但是对于某些浏览器来说,这很好用,为什么?

问题描述 投票:0回答:1

我是jack junior的Web开发人员,在基于Node的聊天应用程序中遇到了一些问题。那就是显示用户发送消息的时间。您可以在我的客户端Main.js文件中看到这样的代码。

// Submit the form
  $('form').submit(async e => {
    e.preventDefault();
    let time = await getTime();
    socket.emit('brodcast', putUserMsg( $('#msg').val(), time));

    $('#msg').val('');
    return false;
  });

function getTime(){
  // For reference 
  // Create instance of Date and get the notation 
  // const notation = new Date().toLocaleString().split(' ')[2];

  //split the time zone
  // const timearr = new Date().toLocaleString().split(' ')[1].split(':');

  return `${
    new Date()
      .toLocaleString()
      .split(' ')[1]
      .split(':')[0]
  }:${
    new Date()
      .toLocaleString()
      .split(' ')[1]
      .split(':')[1]
  } ${new Date().toLocaleString().split(' ')[2]}`;
}

// Return object 
function putUserMsg(msg, time){
  return{
      msg,
      time
  }
}

[这是我在chrome浏览器中的移动视图,您会注意到,当消息类型并按Enter键时,显示的时间是不确定的,为什么会发生。但是我也正在尝试使用类似Ucbrower的其他浏览器,效果很好。为什么会发生?同样,在我的laptop上,我的计算机运行得很好,唯一的问题是为什么它们没有在Chrome浏览器中显示?

预先感谢您的帮助!

javascript express socket.io chat
1个回答
0
投票

我不知道为什么它不能在其他浏览器上运行,但不能在Chrome上运行,但是让我给您一个一般性的建议:保持尽可能简单。

您正在对Date对象执行各种操作,这些操作很难遵循和调试。您只需要按原样发送Date对象,它将自动转换为Date()。toISOString()。该字符串看起来像2020-04-02T23:51:13.866Z,是唯一需要存储的字符串。这是通用的UTC时间,不受您所在地区和夏令时的影响。

所以您的socketIO发射应该看起来像这样:

 socket.emit('brodcast', putUserMsg( $('#msg').val(), new Date()));

稍后,您可以在用户界面中对日期进行所需的操作,并根据需要显示它。一旦从服务器接收到日期字符串(之前发送日期对象时自动创建的日期字符串),您就可以执行以下操作:

<p>{new Date(timeStringFromServer).toLocaleTimeString()}</p>//This will create a Date object from the string, and allow you to manipulate it.

但是您通过socket.io/ajax发送的东西应该总是和new Date()一样简单。此外,我建议使用Moment.js作为日期。

© www.soinside.com 2019 - 2024. All rights reserved.