Skip to content
This repository has been archived by the owner on Dec 15, 2023. It is now read-only.

Commit

Permalink
Add clientside Time
Browse files Browse the repository at this point in the history
  • Loading branch information
Julien Brisson committed Jan 27, 2022
1 parent 0ce10f9 commit 576ce44
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 19 deletions.
1 change: 0 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
16 changes: 0 additions & 16 deletions helpers/messaging.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
24 changes: 22 additions & 2 deletions public/js/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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);

Expand All @@ -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}`;
}

0 comments on commit 576ce44

Please sign in to comment.