Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding date format #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,37 @@
//This function takes a Unix timestamp and an optional length parameter,
//and returns a human-readable time difference in the past or future.
function timelydiff(timestamp, length = null) {
function timelydiff(timestamp, length = null, dateFormat = "default") {
// handliing check if the timestamp type provided is a number
if (typeof timestamp !== "number" || isNaN(timestamp)) {
if (typeof timestamp !== "number" || isNaN(timestamp) || timestamp <= 0) {
throw new Error("Invalid timestamp provided.");
}
// handliing check if the length type provided is a string
if (length !== null && typeof length !== "string") {
throw new Error("Invalid length parameter.");
}

// Error handling for dateFormat
const validDateFormats = ["default", "dd/mm/yyyy", "mm/dd/yyyy"];
if (!validDateFormats.includes(dateFormat)) {
throw new Error("Invalid date format. Please choose a valid date format ('default', 'dd/mm/yyyy', or 'mm/dd/yyyy').");
}


//Calculate the time difference between the current time and the timestamp, in seconds.
let timeDifference = (Date.now() - timestamp) / 1000;
let timeDirection = null;

function formatDate(date) {
if (dateFormat === "dd/mm/yyyy") {
return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
} else if (dateFormat === "mm/dd/yyyy") {
return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
} else {
// default format
return date.toDateString();
}
}

//Determine whether the time difference is in the past or future (is negative)
//and sets the timeDirection variable accordingly.
//It also takes the absolute value of timeDifference in case it's negative.
Expand Down