gpt4 book ai didi

javascript - 为简单的 Firebase 聊天添加时间

转载 作者:行者123 更新时间:2023-12-02 17:26:28 25 4
gpt4 key购买 nike

我正在尝试在简单的 Firebase 聊天中添加时间指示,但我根本无法让它工作。

我尝试使用:

var time = new Date() 或
var time = new Date().getTime()

但 Firebase 似乎无法识别它。

有人知道如何将时间与消息一起打印吗?

提前致谢!

我的代码如下所示:

<!doctype html>
<html>
<head>
<script src='https://cdn.firebase.com/js/client/1.0.11/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
<style>


</style>

<title>
Live
</title>
</head>

<header style="background: #1E2E3C; height:20px; min-width:640px">
<p style="color: white; font-family: helvetica; margin: 0px 8px 0px 0px ;text- align:right;font-size:16px"><span title="Close Window to LOGOUT">Chat Messenger </span></p>

</header>

<body style="background: white; margin: 0px;padding:0px">



<div id='messagesDiv' style="height:300px; min-width:600px; overflow:auto; padding:10px; margin:8px; background: #ECF2F6; color: #1E2E3C; font-family: helvetica;font-size:18px;border- radius:4px;"></div>

<div>
<input type='text' id='nameInput' placeholder='User Name' style="width:200px;height:25px; margin:1px 0px 4px 8px; background: white;border-radius:4px; border: 3px solid #E6ECF2; font-family: helvetica; color: #1E2E3C"><br>

<span title="Press ENTER to send message">
<input type='text' id='messageInput' placeholder='Message' style="width:610px; height:25px; margin:4px 8px 8px 8px; background: white;border-radius:4px; border: 3px solid #E6ECF2; font-family: helvetica; color: #1E2E3C">
</span>

</div>




<script>

var myDataRef = new Firebase('https://xxxxxxxx.firebaseio.com');
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();

myDataRef.push({name: name, text: text});
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ' )).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>

最佳答案

从 Firebase 获取时间的一种方法是在 .push() 消息时使用 Firebase.ServerValue.TIMESTAMP

像这样 myDataRef.push({name: name, text: text, time: Firebase.Server.TIMESTAMP});

由于 Firebase Timestamp是自UNIX纪元以来的时间,以毫秒为单位,在使用之前需要对其进行转换。此功能可能会帮助您:

time = function (timestamp) { // Convert UNIX epoch time into human readble time.
var epoch = new Date(timestamp);
var date = epoch.toUTCString();
return date;
}

最后,你的显示逻辑可能是这样的:

myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
var t = time(message.time);
displayChatMessage(message.name, message.text, t);
});

关于javascript - 为简单的 Firebase 聊天添加时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23460219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com