repos / neovimcraft

website that makes it easy to find neovim plugins
git clone https://github.com/neurosnap/neovimcraft.git

neovimcraft / src
Eric Bower · 27 Nov 22

date.ts

 1const zero = (num: number) => (num < 10 ? `0${num}` : `${num}`);
 2export const format = (date: Date) => {
 3  return `${date.getFullYear()}-${zero(date.getMonth() + 1)}-${
 4    zero(date.getDate())
 5  }`;
 6};
 7
 8const units: { unit: Intl.RelativeTimeFormatUnit; ms: number }[] = [
 9  { unit: "year", ms: 31536000000 },
10  { unit: "month", ms: 2628000000 },
11  { unit: "day", ms: 86400000 },
12  { unit: "hour", ms: 3600000 },
13  { unit: "minute", ms: 60000 },
14  { unit: "second", ms: 1000 },
15];
16const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
17
18/**
19 * Get language-sensitive relative time message from Dates.
20 * @param relative  - the relative dateTime, generally is in the past or future
21 * @param pivot     - the dateTime of reference, generally is the current time
22 */
23export function relativeTimeFromDates(
24  relative: Date | null,
25  pivot: Date = new Date(),
26): string {
27  if (!relative) return "";
28  const elapsed = relative.getTime() - pivot.getTime();
29  return relativeTimeFromElapsed(elapsed);
30}
31
32/**
33 * Get language-sensitive relative time message from elapsed time.
34 * @param elapsed   - the elapsed time in milliseconds
35 */
36export function relativeTimeFromElapsed(elapsed: number): string {
37  for (const { unit, ms } of units) {
38    if (Math.abs(elapsed) >= ms || unit === "second") {
39      return rtf.format(Math.round(elapsed / ms), unit);
40    }
41  }
42  return "";
43}