Reputation: 1382
Am trying to print the date from script.js coming from mongodb but am getting the below error
Uncaught TypeError: date.toLocaleTimeString is not a function
function db_old_msgs(old_msg) {
$('.chat-messages').append('<span class="msg"><b>' + old_msg.nick + ': </b>' + old_msg.msg +" "+FormatTime(old_msg.created) + "</span><br/>");
}
function FormatTime(time, prefix = "") {
var date = Date.parse(time);
return ((typeof time != "undefined") ? prefix + date.toLocaleTimeString() : "");
}
I tried the above without the function FormatTime like "+ old_msg.created.toLocaleTimeString() +" but I get the same error.
The time format that is received from db is 2021-12-16T13:22:01.600+00:00.
Dates are being displayed correctly which are coming from server.js
socket.broadcast.emit('msg', {from: users[socket.id],message: message, time:newMsg.created.toLocaleTimeString()})
Many thanks
Upvotes: 0
Views: 1598
Reputation: 1382
The date was coming as string from the server so I had to convert it to date and then pass the function toLocaleTimeString()
function db_old_msgs(old_msg) {
var dbtime=new Date(old_msg.created);
var formattedDate = dbtime.toLocaleTimeString();
$('.chat-messages').append('<span class="msg"><b>' + old_msg.nick + ': </b>' + old_msg.msg +" "+formattedDate + "</span><br/>");
}
Upvotes: 3