import HolyTime from 'holy-time'const past = new HolyTime('2023-01-01T00:00:00.000Z')const future = new HolyTime('2023-01-01T02:30:00.000Z')HolyTime.relativeFromTo(past, future)// Returns: "in 2 hours"HolyTime.relativeFromTo(future, past)// Returns: "2 hours ago"
Get relative time from the instance to another date:
const date = new HolyTime('2023-01-01T00:00:00.000Z')const other = new HolyTime('2023-01-01T05:00:00.000Z')date.getRelativeTo(other)// Returns: "in 5 hours"
Get relative time from another date to the instance:
const date = new HolyTime('2023-01-01T05:00:00.000Z')const other = new HolyTime('2023-01-01T00:00:00.000Z')date.getRelativeFrom(other)// Returns: "in 5 hours"
const date = new HolyTime('2023-01-01T01:02:03.000Z')const duration = HolyTime.since(date)duration.in('seconds') // Time in seconds since the dateduration.in('hours') // Time in hours since the dateduration.in('days') // Time in days since the date
function formatPostTime(postDate: Date): string { const post = new HolyTime(postDate) const now = HolyTime.now() return post.getRelativeTo(now)}formatPostTime(new Date('2023-06-15T10:00:00.000Z'))// Returns: "5 hours ago" (if current time is 3pm same day)
function smartRelativeTime(date: Date): string { const time = new HolyTime(date) const duration = HolyTime.since(date) // For very recent times, show exact time if (duration.in('minutes') < 5) { return time.format('HH:mm') } // For same day, show relative if (time.isSame(HolyTime.now(), 'day')) { return time.getRelativeTo(HolyTime.now()) } // For older dates, show full date return time.format('YYYY-MM-DD')}
The RELATIVE_MAP automatically handles pluralization:
// Singular forms (1 unit)"a minute ago" // Not "1 minute ago""an hour ago" // Not "1 hour ago""a day ago" // Not "1 day ago"// Plural forms (2+ units)"2 minutes ago""5 hours ago""3 days ago"
The relative time calculation always uses the absolute difference between dates, ensuring consistent output regardless of date order.