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

[Feature]: Relative time formatting #27

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
69 changes: 69 additions & 0 deletions src/__tests__/formatRelative.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { describe, it, expect } from "vitest"
import { formatRelative } from "../formatRelative"
process.env.TZ = "America/New_York"

describe("format", () => {
it('renders "minutes" relative date', () => {
expect(
formatRelative(new Date(new Date().getTime() - 1000 * 60 * 4), {
unit: "minute",
}),
).toEqual("4 minutes ago")
})

it('renders "long" relative date', () => {
expect(
formatRelative(new Date(new Date().setMonth(new Date().getMonth() - 2)), {
style: "long",
}),
).toEqual("2 months ago")
})

it('renders "short" relative date', () => {
expect(
formatRelative(
new Date(new Date().setFullYear(new Date().getFullYear() - 2)),
{
style: "short",
},
),
).toEqual("2 yr. ago")
})

it('renders "narrow" relative date', () => {
expect(
formatRelative(new Date(new Date().setMonth(new Date().getMonth() - 2)), {
style: "narrow",
}),
).toEqual("2mo ago")
})

it("renders ukrainian relative date", () => {
expect(
formatRelative(new Date(new Date().setMonth(new Date().getMonth() - 2)), {
locale: "uk",
}),
).toEqual("2 місяці тому")
})

it("renders relative date with a unit", () => {
expect(
formatRelative(
new Date(new Date().getTime() - 60 * 24 * 60 * 60 * 1000),
{
unit: "days",
},
),
).toEqual("60 days ago")
})
})

// describe("format with a timezone", () => {
// it("can format a date with a timezone", () => {
// expect(
// formatRelative("2024-02-27T20:00:00-0500", {
// tz: "Europe/Amsterdam",
// }),
// ).toBe("7 11:30:10")
// })
// })
66 changes: 66 additions & 0 deletions src/formatRelative.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { date } from "./date"
import type { DateInput, RelativeFormatOptions } from "./types"
import { deviceLocale } from "./deviceLocale"

export function formatRelative(
inputDate: DateInput,
options?: RelativeFormatOptions,
originDate?: DateInput,
) {
let { unit, locale } = options || {}

if (!locale || locale === "device") {
locale = deviceLocale()
}

// Remove the 's' from the end of the unit if it exists
// e.g. 'days' -> 'day'
if (unit)
unit = (
unit.endsWith("s") ? unit.slice(0, -1) : unit
) as Intl.RelativeTimeFormatUnit

const date1 = date(inputDate)
const date2 = originDate ? date(originDate) : date(new Date())

// Get the amount of seconds between the given date and now
const deltaSeconds = Math.round((date1.getTime() - date2.getTime()) / 1000)

// Array reprsenting one minute, hour, day, week, month, etc in seconds
const cutoffs = [
60, // 1 minute
3600, // 1 hour
86400, // 1 day
86400 * 7, // 1 week
86400 * 30, // 1 month
86400 * 91, // 1 quarter
86400 * 365, // 1 year
Infinity, // Infinity days
]

// Array equivalent to the above but in the string representation of the units
const units: Intl.RelativeTimeFormatUnit[] = [
"second",
"minute",
"hour",
"day",
"week",
"month",
"quarter",
"year",
]

// Grab the ideal cutoff unit
const unitIndex = unit
? units.findIndex((elem) => elem === unit)
: cutoffs.findIndex((cutoff) => cutoff > Math.abs(deltaSeconds))

// Get the divisor to divide from the seconds. E.g. if our unit is "day" our divisor
// is one day in seconds, so we can divide our seconds by this to get the # of days
const divisor = unitIndex ? cutoffs[unitIndex - 1] : 1

// Intl.RelativeTimeFormat do its magic
const rtf = new Intl.RelativeTimeFormat(locale, options)

return rtf.format(Math.round(deltaSeconds / divisor), units[unitIndex])
}
4 changes: 2 additions & 2 deletions src/offset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function relativeTime(d: Date, timeZone: string): Date {
parts[part.type as keyof typeof parts] = part.value
})
return new Date(
`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`
`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`,
)
}

Expand All @@ -49,7 +49,7 @@ function relativeTime(d: Date, timeZone: string): Date {
export function offset(
utcTime: DateInput,
tzA = "UTC",
tzB = "device"
tzB = "device",
): string {
tzB = tzB === "device" ? deviceTZ() ?? "utc" : tzB
const d = date(utcTime)
Expand Down
18 changes: 16 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export type FilledPart = Part & { value: string }
export type FormatPattern = [
pattern: FormatToken | string,
option: Partial<Record<Intl.DateTimeFormatPartTypes, string>>,
exp?: RegExp
exp?: RegExp,
]

/**
Expand Down Expand Up @@ -159,11 +159,25 @@ export interface FormatOptions {
*/
genitive?: boolean
/**
* A function to filter parts.
* Converts the given date option to the timezone provided.
*/
tz?: string
/**
* A function to filter parts.
*/
partFilter?: (part: Part) => boolean
}

export interface RelativeFormatOptions extends Intl.RelativeTimeFormatOptions {
/**
* A unit of time to format the date relative to.
* ```js
* ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second']
* ```
*/
unit?: Intl.RelativeTimeFormatUnit
/**
* A locale or 'device' by default.
*/
locale?: string
}