Skip to content

Instantly share code, notes, and snippets.

<div class="container mt-4 mb-2" style="max-width: 600px">
<h2>Human Feed</h2>
<p class="lead">This is a demo of human-friendly dates <!-- ... --></p>
<div class="mx-auto text-center">
<p class="lead mb-1">View in</p>
<div class="btn-group mb-2" id="localeControls">
<button
id="localeControl-en"
/**
* All dates are displayed relative to this
*/
const baseTime: number = Date.now();
/**
* A post in our data set
*/
interface Post {
name: string;
/**
* Supported locales
*/
type Locale = "en" | "ar";
/**
* Determines localized UI elements and data shown
*/
let currentLocale: Locale = "en";
// Some configrable constants we need to do our work:
/**
* Past this number of days we'll no longer display the
* day of the week and instead we'll display the date
* with the month
*/
const DATE_WITH_MONTH_THRESHOLD_IN_DAYS: number = 6;
/**
const MILLISECONDS_TO_SECONDS: number = 0.001;
/**
* Convert milliseconds to seconds
*/
function millisecondsToSeconds(milliseconds: number): number {
return Math.floor(milliseconds * MILLISECONDS_TO_SECONDS);
}
function humanFriendlyDate(date: Date): string {
const unixTimestamp: number = millisecondsToSeconds(date.valueOf());
const now: number = millisecondsToSeconds(Date.now());
const diffComponents: DateTimeComponents =
getDateTimeComponents(now - unixTimestamp);
// ...
}
function humanFriendlyDate(date: Date): string {
const unixTimestamp: number = millisecondsToSeconds(date.valueOf());
const now: number = millisecondsToSeconds(Date.now());
const diffComponents: DateTimeComponents =
getDateTimeComponents(now - unixTimestamp);
const { years, months, days, hours, minutes, seconds } = diffComponents;
/**
* Options when formatting a date
*/
interface DateFormatOptions {
includeYear?: Boolean;
}
/**
* For English, format a date with given options, adding an ordinal
* e.g. "May 1st, 1992" (note the "1st"). For non-English locales,
/**
* Past this number of days we'll no longer display the
* day of the week and instead we'll display the date
* with the month
*/
const DATE_WITH_MONTH_THRESHOLD_IN_DAYS: number = 6;
function humanFriendlyDate(date: Date): string {
// ...
/**
* Past this number of hours we'll no longer display "hours
* ago" and instead we'll display "today"
*/
const TODAY_AT_THRESHOLD_IN_HOURS: number = 12;
function humanFriendlyDate(date: Date): string {
// ...