Skip to content
WingoUI
ComponentsTemplatesDocsPricingAI agentsBlogChangelogContact
Components
Buttons & Actions
ButtonButton GroupCopy ButtonDelete ButtonTheme ToggleToggleToggle Group
Inputs
Avatar UploadCalendarCheckboxColor PickerComboboxCountry SelectCron PickerCurrency InputDate PickerDate Range PickerDate Time PickerDuration PickerEmail InputEmoji PickerFile UploadFilter BuilderInputInput GroupListboxMasked InputMention InputMonth PickerMulti SelectNumber InputOTP InputPassword InputPhone InputRadio GroupRatingSearch InputSegmented ControlSelectSignature PadSliderSwitchTag InputTextareaTime PickerTimezone SelectTree Select
Forms
Address InputBooking WidgetCSV ImportFieldForm WizardInline EditInvoice line itemsRich Text EditorSchema Builder
Navigation
Back To TopBounce SidebarBreadcrumbCommand MenuGlobal SearchGooey NavHook SidebarNav MenuNav TabsPaginationProximity SidebarScroll ProgressSidebarStepsTable Of ContentsTabsTopbarUser MenuWorkspace Switcher
Overlays
Alert DialogContext MenuDialogDrawerDropdown MenuFamily DrawerHover CardPopoverShare DialogSheetShortcuts DialogTooltipTour
Feedback
AlertBannerCookie ConsentEmoji ReactionEmpty StateNotification BellNotification CenterProgressRoute ProgressSetup ChecklistSkeletonSpinnerToast
Data Display
Approval FlowAvatarBadgeCalendar ViewCode BlockComment ThreadContact cardCountdownDescription ListDiff ViewerFile ListFile managerFolderGanttJSON ViewerKbdLog ViewerMarkdownPresenceSchedulerTagTimelineTree View
Tables & Lists
Audit LogData TableDeal PipelineEditable GridKanbanListMembers tablePermissions MatrixTableTask ListVirtual List
Charts & Stats
Animated CounterArea chartBar chartDonut chartFunnel chartGaugeGitHub ActivityHeatmap calendarLeaderboardLine chartRadar chartRadial barSparklineStat CardTrackerTrend badge
Layout
AccordionApp ShellCardCollapsibleDetail LayoutEntity HeaderPage HeaderScroll AreaSeparatorSettings LayoutSplit ViewToolbar
Media
Audio PlayerCarouselCSV ViewerDOCX EditorDOCX ViewerExcel ViewerFile SystemImage compareImage CropperImage GalleryImage LightboxLocation MapPDF ViewerPowerPoint ViewerQR CodeStep PlayerVideo Player
AI Kit
Agent Status CardChat MessageChat ThreadChat WidgetConversation ListFluid OrbGrid RevealMatrix OrbModel PickerPrompt InputReasoning IndicatorRule BuilderSuggestion ChipsTool Call TimelineUsage MeterVoice InputWorkflow Canvas
Text & Effects
Background PatternGravity LettersMarqueeTerminalText AnimateText Rotate
Mobile
Action SheetBottom Tab BarFABHaptic ButtonHero HeaderInstall PromptLarge Title HeaderNotification BannerOnboarding CarouselPicker WheelPull To RefreshSlide To ConfirmSticky CTA BarSwipe DeckSwipeable Tabs
Commerce
Cart drawerCategory pickerCheckout stepsCoupon inputFavorite buttonFilter panelListing cardListing gridOrder trackerPricePrice rangePricing tableProduct galleryQuantity stepperReviewsSeller card
Marketing Sections
App Download SectionBlog Cards SectionCTA SectionFAQ SectionFeature GridFeature ShowcaseHero SectionIntegrations SectionLogo CloudMarketing FooterMarketing HeaderMarketing SectionNewsletter SectionPricing SectionStats SectionSteps SectionTeam SectionTestimonials SectionTimeline SectionVideo Section
Blocks
Admin Dashboard PageAdmin ShellAI Chat PageAPI Keys PageAutomation Builder PageCheckout PageCRM Contact PageCRM Pipeline PageError PagesInbox PageInvoice PageKPI DashboardListing Detail PageLogin PageMarketplace Home PageMarketplace Search PageMarketplace ShellMobile App HomeOnboarding FlowOrder History PagePost Listing WizardPricing PageProfile PageRegister PageSettings PageUsers Admin Page
Templates
About PageAcademy PageAccessibility PageAffiliate PageAgency PageAI Product PageAppointment Booking PageBlog PageBlog Post PageBug Bounty PageCareers PageChangelog PageCommunity PageCompare PageContact PageCustomer Story PageCustomers PageDemo Booking PageDevelopers PageDocs Home PageDownload PageEnterprise PageEvents PageExperts PageFAQ PageFeature PageGlossary PageHelp Article PageHelp Center PageHome Services PageImpact PageIntegration Detail PageIntegrations PageJob Detail PageLanding PageLaunch PageLegal PageManifesto PagePortfolio PagePress PageProduct Tour PagePromo PageReal Estate PageReferral PageResearch Report PageRestaurant PageRoadmap PageROI Calculator PageSecurity PageSolutions PageStartups PageStatus PageStorefront PageSwitch PageTemplate Gallery PageTravel PageWaitlist PageYear in Review Page
Hooks & Utilities
AI ChatChart kitCommerceDate utilsFile exportFile typesFiltersForm validationHapticsInvoicingMotion presetsNavigationNumber formatRelative timeRomanian locationsSpreadsheetText matchTonesUIProvideruseClipboarduseConsentuseControllableStateuseCooldownuseDebounceuseKeyboardInsetuseLocaleuseLongPressuseMediaControlsuseMediaQueryuseOverflowItemsusePersistedStateuseScrollEdgesuseScrollStateuseSelectionuseShortcutuseStickToBottom
GalleryTheme

Hooks & Utilities

Relative time

Hooks & Utilities

Relative time TypeScript helper for React

Number formatRomanian locations
Live props
Options
locale
style
format
grouped
  1. Home
  2. Components
  3. Hooks & Utilities
  4. Relative time
Pro

Relative time TypeScript helper for React

v1.0.0·Added in 1.0.0

Hydration-safe timestamps for feeds and comments: "5 min. ago", day groups like Today / Yesterday, clocks and full dates.

The feed shows the same events with relative times that tick every minute, grouped under Today, Yesterday and weekday headings. Switch the locale, the style and the format in the playground to compare "5 min. ago" with "vor 5 Min.", clocks and full dates. Hover a time to see the full date.

Relative time is a Pro React helper in the React hooks and utilities category, written in TypeScript for React 19. It installs as source with npx wingo-ui@latest add relative-time, together with Date utils.

Add to a project

Requirements: React 19, in Next.js (App Router or Pages), Vite or React Router. Installation guide · Next.js setup · Vite setup

npx wingo-ui@latest add relative-time

Relative time is part of Pro, with 298 more Pro items: $8 a month or $150 once. 14-day refund before you download any Pro item. See plans

Usage

Import formatTimestamp from @/lib/relative-time.

import { formatTimestamp, formatFullTimestamp, toDateTimeAttr, useNow } from "@/lib/relative-time"

export function CommentTime({ date }: { date: Date }) {
  const now = useNow()
  return (
    <time dateTime={toDateTimeAttr(date)} title={formatFullTimestamp(date, "en-US")}>
      {formatTimestamp(date, { now, locale: "en-US" })}
    </time>
  )
}

API

  • localedefault "en-US"
    string

    The demo's locale. Every helper takes a locale; components pass the one from useLocale.

  • styledefault "short"
    "long" | "short" | "narrow"

    RelativeTimeOptions.style: "5 minutes ago" (long) or "5 min. ago" (short).

  • formatdefault "relative"
    "relative" | "time" | "date" | "datetime"

    TimestampOptions.format for formatTimestamp: relative text, the clock, the date or both.

  • groupeddefault true
    boolean

    The demo groups the feed with groupByDay.

  • formatTimestamp
    (value, options: { now: number | null; locale?: string; format?: TimestampFormat; style?; maxDays? }) => string

    One call for any row timestamp. With now null, relative falls back to "22.09.2026, 16:40".

Parts

  • useNow

    hook

    The current time rounded down to interval ms (default 60 000), re-rendering when it ticks and when the tab wakes up. null on the server and during hydration: render a date then, and relative text once it is a number. Signature: (interval?: number) => number | null.

  • formatRelativeTime

    function

    "now", "5 min. ago", "3 hr. ago", "yesterday", "3 days ago", "2 wk. ago", then the date past maxDays (28). Future times read "in 5 min.", "tomorrow". Signature: (value: Date | string | number, options: { now: number; locale?: string; style?: RelativeTimeStyle; maxDays?: number; dateOptions?: Intl.DateTimeFormatOptions }) => string.

  • formatDayGroupLabel

    function

    "Today", "Yesterday", "Tomorrow", a weekday within the last week ("Monday"), then the date. Signature: (value, now: number | null, locale?: string, dateOptions?) => string.

  • groupByDay

    function

    Consecutive day groups { key, date, label, items }, newest first by default; items without a valid time go last under undatedLabel ("Earlier"). Signature: <T>(items: readonly T[], getTime: (item: T) => TimeInput | null | undefined, options: { now: number | null; locale?: string; order?: "desc" | "asc" | "none"; undatedLabel?: string }) => DayGroup<T>[].

  • formatClock

    function

    "4:40 PM" or "16:40"; "Thursday, September 24, 2026 at 4:40 PM" for titles; the ISO string for <time dateTime>. Signature: (value, locale?) => string.

  • formatFullTimestamp

    function

    "4:40 PM" or "16:40"; "Thursday, September 24, 2026 at 4:40 PM" for titles; the ISO string for <time dateTime>. Signature: (value, locale?) => string.

  • toDateTimeAttr

    function

    "4:40 PM" or "16:40"; "Thursday, September 24, 2026 at 4:40 PM" for titles; the ISO string for <time dateTime>. Signature: (value, locale?) => string.

  • toTime

    function

    Parsing and calendar-day math (0 today, -1 yesterday), DST safe. Constants MINUTE, HOUR, DAY. Signature: (value) => number | null.

  • startOfDayTime

    function

    Parsing and calendar-day math (0 today, -1 yesterday), DST safe. Constants MINUTE, HOUR, DAY. Signature: (time) => number.

  • dayDiff

    function

    Parsing and calendar-day math (0 today, -1 yesterday), DST safe. Constants MINUTE, HOUR, DAY. Signature: (time, now) => number.

Examples

Three styles

formatRelativeTime in long, short and narrow; past maxDays (28 by default) it switches to a date.

Chat with day dividers

groupByDay with order asc gives Today, Yesterday and weekday headings; formatClock prints each message's time.

Dependencies

date-utils

Files

  • lib/relative-time.ts

FAQ

Is the Relative time helper free?

The preview, props and docs are free; copying the source needs a Pro plan. See plans.

How do I install Relative time?

Run npx wingo-ui@latest add relative-time. It also adds the Wingo UI item it builds on (Date utils). With shadcn, add the @wingo-ui registry with your API key, then run npx shadcn@latest add @wingo-ui/relative-time.

See also

Date utilslibuseLocalehookNumber formatlib

Used in

Listing cardMarketplace Home PageMobile App HomeKanbanFile managerOrder trackerCountdownData TableDeal PipelineReviewsSeller cardCron Picker

and 44 more.

More React hooks and utilities

Romanian locationslibSpreadsheetlibText matchlibToneslibUIProviderlibuseClipboardhook
All 36 React hooks and utilities
PreviousNumber formatNext Romanian locations

Recent activity

now: null

09/24/2026

  • Emma Carter commented on quote #Q-2026-11809/24/2026, 4:39 PM
  • Invoice #2026-0412 was paid09/24/2026, 4:34 PM
  • Order 1042 left the New Jersey warehouse09/24/2026, 1:40 PM

09/23/2026

  • Liam Brooks added the customer Old Mill Bakery09/23/2026, 2:40 PM

09/21/2026

  • The Northwind Tech LLC contract was signed09/21/2026, 4:40 PM

09/12/2026

  • Invoice #2026-0377 was issued09/12/2026, 4:40 PM