Skip to content

Instantly share code, notes, and snippets.

@kthwaite
Created November 15, 2024 17:12
Show Gist options
  • Save kthwaite/c03be6209af28dd798df1f88d01fa404 to your computer and use it in GitHub Desktop.
Save kthwaite/c03be6209af28dd798df1f88d01fa404 to your computer and use it in GitHub Desktop.
/**
* Converts a timestamp into a human-readable "time since" string
* @param timestamp - Date string or Date object
* @returns Human-readable duration string
*/
export function getTimeSince(timestamp: string | Date): string {
const date =
typeof timestamp === "string" ? new Date(timestamp) : timestamp;
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffSecs = Math.floor(diffMs / 1000);
const diffMins = Math.floor(diffSecs / 60);
const diffHours = Math.floor(diffMins / 60);
const diffDays = Math.floor(diffHours / 24);
// Less than 1 minute
if (diffMins < 1) {
return `${diffSecs} second${diffSecs !== 1 ? "s" : ""} ago`;
}
// Less than 1 hour
if (diffHours < 1) {
return `${diffMins} minute${diffMins !== 1 ? "s" : ""} ago`;
}
// Less than 24 hours
if (diffDays < 1) {
if (diffMins % 60 === 0) {
// Exact hours
return `${diffHours} hour${diffHours !== 1 ? "s" : ""} ago`;
} else {
// Hours and minutes
const remainingMins = diffMins % 60;
return `${diffHours} hour${diffHours !== 1 ? "s" : ""} and ${remainingMins} minute${remainingMins !== 1 ? "s" : ""} ago`;
}
}
// More than 24 hours
return `${diffDays} day${diffDays !== 1 ? "s" : ""} ago`;
}
/**
* Formats a timestamp into a human-readable format: DD-MM-YYYY HH:MM(am/pm)
* @param timestamp - Date string or Date object
* @returns Formatted date string
*/
export function humanizeTimestamp(timestamp: string | Date): string {
const date =
typeof timestamp === "string" ? new Date(timestamp) : timestamp;
// Get day, month, year
const day = date.getDate().toString().padStart(2, "0");
const month = (date.getMonth() + 1).toString().padStart(2, "0"); // getMonth() is 0-based
const year = date.getFullYear();
// Get hours in 12-hour format
let hours = date.getHours();
const ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // Convert 0 to 12
// Get minutes
const minutes = date.getMinutes().toString().padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}${ampm}`;
}
/**
* Formats a timestamp into a human-readable "casual" date string.
* @param timestamp - string timestamp
* @returns Formatted date string
*/
export const humanizeTimestampCasual = (date: string): string => {
const dateObject = new Date(date);
const options: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
};
return dateObject.toLocaleDateString("en-GB", options);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment