diff --git a/app.js b/app.js index c247fb6..5d8f4ee 100644 --- a/app.js +++ b/app.js @@ -54,7 +54,6 @@ function receiveChatMessage(socket, message) { const messageObject = { sender: users.getById(socket.id).username, text: sanitizer.sanitize(message || "hi"), - time: messaging.generateFormattedDate(), }; io.emit(events.MESSAGE, messageObject); diff --git a/helpers/messaging.js b/helpers/messaging.js index d069e73..ca50f1d 100644 --- a/helpers/messaging.js +++ b/helpers/messaging.js @@ -9,25 +9,9 @@ function generateServerMessage(message) { return { sender: BOT_NAME, text: message, - time: generateFormattedDate(), }; } -/** - * Generate a formatted date. - * @return {string} The formatted date. - */ -function generateFormattedDate() { - const now = new Date(); - const format = now.getHours() >= 12 ? "PM" : "AM"; - - const hours = now.getHours().toString().padStart(2, "0"); - const minutes = now.getMinutes().toString().padStart(2, "0"); - - return `${hours}:${minutes} ${format}`; -} - module.exports = { generateServerMessage, - generateFormattedDate, }; diff --git a/public/js/chat.js b/public/js/chat.js index 2b5042a..219691a 100644 --- a/public/js/chat.js +++ b/public/js/chat.js @@ -53,7 +53,7 @@ chatForm.addEventListener(EV_SUBMIT, (e) => { /** * Display an incoming message. - * @param {{sender: string, text: string, time: string}} messageObject The message object to display. + * @param {{sender: string, text: string}} messageObject The message object to display. */ function displayMessage(messageObject) { const container = document.createElement("div"); @@ -70,7 +70,7 @@ function displayMessage(messageObject) { senderParagraph.innerText = messageObject?.sender; const senderTimeSpan = document.createElement("span"); - senderTimeSpan.innerText = messageObject?.time; + senderTimeSpan.innerText = getFormattedTime(); senderParagraph.appendChild(senderTimeSpan); @@ -93,3 +93,23 @@ function displayUsernames(usernamesList) { usersContainer.appendChild(user); }); } + +/** + * Gets the current time and formats it to x:xx PM / AM + * @return {string} The current formatted time. + */ +function getFormattedTime() { + const now = new Date(); + + const suffix = now.getHours() >= 12 ? " PM" : " AM"; + + let hours = now.getHours() % 12; + if (hours == 0) hours = 12; + + const minutes = now.getMinutes().toString().padStart(2, "0"); + if (minutes < 10) { + minutes = "0" + minutes.toString(); + } + + return `${hours}:${minutes} ${suffix}`; +} \ No newline at end of file