Your feed says "5 minutes ago", your chat list says "yesterday", and your sync banner says "in 2 hours". In English those labels look done. Switch the app to Polish and a hand-built helper still prints English words or picks the wrong plural. Switch to German and a label glued into a sentence starts with a capital letter in the middle of a line. Look at a post from late the night before and the app may call it "2 days ago" or "yesterday" depending on how the helper counts. Relative time formatting is locale data plus a few decisions your code has to make on purpose. This guide shows how to replace the helper with platform formatters, choose units correctly, embed the result safely, and test it before release.
It assumes you already format absolute dates with locale-aware APIs, as covered in our guide to localizing app dates, times, and numbers, and that you avoid building sentences from fragments, as explained in stop concatenating strings.
The short answer
- Delete the hand-written time-ago helper and call the platform relative time formatter with the locale your app actually resolved.
- Decide which unit to show with explicit rules: elapsed time for seconds, minutes, and hours, calendar days in the viewer's time zone for day-level labels.
- Show the formatted phrase on its own, or place it in one complete translatable sentence. Never append it to a translated prefix.
- Switch to an absolute date past a cutoff, refresh live labels on a cadence that matches the unit, and keep the exact timestamp for tooltips and accessibility.
- Test boundary times around midnight and unit thresholds in a small matrix of plural-rich and right-to-left locales.
Why hand-built time-ago helpers fail
The most-visited answers still teach the helper. The Stack Overflow question Swift convert time to time ago has roughly 24,000 views, and its top answer returns English literals such as "year ago" and "days ago" chosen with a == 1 check. The Android equivalent, How to create a localized time ago String on Android, starts from a conference app helper and asks how to localize it at all. Both are practitioner reports.
A helper like that fails in three ways at once:
- Plurals. CLDR stores relative-time patterns per unit and per plural category. Unicode's LDML dates specification defines
relativeTimePatternentries keyed by acountofzero,one,two,few,many, orother. A one-or-many branch cannot express Polish, Russian, or Arabic. - Named phrases. Many languages have dedicated words for yesterday, tomorrow, last week, and next week. A numeric helper never produces them, and a translator cannot add them through a single "%d days ago" key.
- Word order. The number, unit, and direction marker move around the sentence. Japanese puts the time expression mid-sentence, which is what one developer hit when trying to insert a relative phrase into a sentence (RelativeDateTimeFormatter context for localised string).
Small slips ship to production, too. GetStream's Android chat SDK reported an untranslated "Active just now" status.
Use the platform relative time formatter
Apple platforms, Android, and the web each ship relative time formatting backed by locale data. Your code passes the right locale, chooses the value and unit, and picks a style.
iOS and macOS
Apple's RelativeDateTimeFormatter is available from iOS 13. It exposes dateTimeStyle for named versus numeric output, unitsStyle for full, short, or abbreviated units, and formattingContext for capitalization. On iOS 15 and later, Date.RelativeFormatStyle offers the same choice through its presentation setting: .numeric produces "1 week ago" and .named produces "last week". Its initializer also takes locale, calendar, and capitalizationContext.
// appLocale and appCalendar come from your language resolution, not a literal.
let style = Date.RelativeFormatStyle(
presentation: .named,
unitsStyle: .wide,
locale: appLocale,
calendar: appCalendar,
capitalizationContext: .standalone
)
let label = postedAt.formatted(style)
// iOS 13 and 14
let formatter = RelativeDateTimeFormatter()
formatter.locale = appLocale
formatter.dateTimeStyle = .named
formatter.formattingContext = .standalone
let legacyLabel = formatter.localizedString(for: postedAt, relativeTo: now)
For SwiftUI screens, Text.DateStyle.relative (iOS 14 and later) displays a date relative to now and keeps itself current. A developer who built labels with RelativeDateTimeFormatter reported that the view froze at "10 seconds ago" until reload, and a top answer pointed to this style (Live update relative time in SwiftUI). It gives you less control over wording, so use it where a live counter matters more than named phrases.
Android
Use android.icu.text.RelativeDateTimeFormatter, available from API 24. It has a getInstance(ULocale) factory and an overload that takes a number format, style, and capitalization context. On API 24 to 27 you call format(quantity, Direction, RelativeUnit); API 28 adds format(offset, RelativeDateTimeUnit) and formatNumeric. The class also formats named forms such as "last Sunday" through AbsoluteUnit. It supports one unit per phrase and does not parse.
// appLocale is the locale your per-app language setting resolved.
val fmt = RelativeDateTimeFormatter.getInstance(ULocale.forLocale(appLocale))
// API 28+: negative offsets are in the past.
val label = fmt.format(-5.0, RelativeDateTimeFormatter.RelativeDateTimeUnit.MINUTE)
// API 24-27
val older = fmt.format(5.0, RelativeDateTimeFormatter.Direction.LAST,
RelativeDateTimeFormatter.RelativeUnit.MINUTES)
DateUtils.getRelativeTimeSpanString is the older shortcut. On Android, pass the app's resolved locale to android.icu RelativeDateTimeFormatter instead of relying on DateUtils, because DateUtils relative strings take no locale argument and format with the process default locale and time zone. The AOSP DateUtils source passes Locale.getDefault() and TimeZone.getDefault() straight into its formatter. Whether that matches the language a user picked inside your app depends on how your language switching updates the process default, which is not something a list screen should have to guess. Developers who overrode the app locale reported years ago that this method kept producing device-language text (default locale for getRelativeTimeSpanString). Passing the locale explicitly removes the question. If you support per-app languages, take that locale from the same place described in our guide to per-app language preferences on Android.
Web and cross-platform code
Intl.RelativeTimeFormat has been Baseline across browsers since September 2020. Its numeric option defaults to "always". Set it to "auto" to get "yesterday", "today", and "tomorrow" where the locale has those words. The V8 team's feature article shows what the default does with zero: "always" produces "in 0 days".
const rtf = new Intl.RelativeTimeFormat(appLocale, { numeric: "auto", style: "long" });
rtf.format(-1, "day"); // "yesterday" in English
rtf.format(-3, "hour"); // "3 hours ago" in English
format() takes a value and a unit that you supply. It does not compute the difference between two dates or choose the unit. That decision is yours on the web, and it deserves the same care on mobile.
Choose units by calendar day, not by elapsed hours
One developer reported that RelativeDateTimeFormatter in named style showed a timestamp from about 45 hours earlier as "yesterday" (RelativeDateTimeFormatter says a date from 2 days ago is yesterday). Reading the timestamps in the report, the likely cause is that the interval was one day and 21 hours, the largest whole unit was one day, and named style turned one day into "yesterday", even though the post sat two calendar dates back for most readers. A helper that divides elapsed hours by 24 makes the same mistake.
Pick day-level labels from the calendar-day difference in the viewer's time zone, not from elapsed hours, so yesterday always means the previous calendar date for that reader. A post from 40 hours ago may be yesterday or two days ago depending on the hour it was posted, and only the calendar can tell. Compute the day offset yourself, then hand it to the formatter as a value and unit:
var cal = appCalendar
cal.timeZone = viewerTimeZone
let days = cal.dateComponents([.day],
from: cal.startOfDay(for: postedAt),
to: cal.startOfDay(for: now)).day ?? 0
let label = formatter.localizedString(from: DateComponents(day: -days))
RelativeDateTimeFormatter accepts date components directly through localizedString(from:), Android takes the offset in format, and Intl.RelativeTimeFormat takes it as the value. The same day offset then produces the same answer on every platform.
These rules work well as a starting point. They are recommendations, not platform guarantees:
| Elapsed time | Unit to show | Basis |
|---|---|---|
| Under 1 minute | Now, or seconds | Elapsed time |
| Under 1 hour | Minutes | Elapsed time |
| Under 6 to 12 hours, same calendar day | Hours | Elapsed time |
| Different calendar day, within 6 days | Named day or days | Calendar days in the viewer's zone |
| 7 days or more | Absolute date | Locale date format |
Set an absolute-date cutoff as well. BleepingSwift's SwiftUI relative time guide notes that "52 weeks ago" is not helpful and suggests falling back to a standard date for older items. The js-date-timezone.com time-ago guide also treats yesterday as a calendar-day concept in the user's zone for web code. Apply that rule to every platform you ship so iOS, Android, and web agree on the same timestamp.
Embed relative phrases without breaking the sentence
Apple's documentation for RelativeDateTimeFormatter says to use phrases such as "1 hour ago" and "yesterday" as standalone strings, because embedding them in other strings "may not be grammatically correct." Most of the tutorials linked in this guide skip that warning.
Thunderbird's K-9 Mail shows what happens. It appended the output of DateUtils.getRelativeTimeSpanString() to the German label "Nächster Abruf", and a German user saw "In" with a capital letter on some Android versions and "in" on others (thunderbird-android issue 4858). A maintainer replied that the appended output looked different depending on the Android version. The DateUtils reference itself shows future spans formatted like "In 42 minutes", with a capital I.
Use a formatted relative phrase as a standalone label or inside one translatable sentence with a capitalization context, because appending it to a translated prefix breaks case and word order. In practice:
- Standalone label. Put the phrase in its own view, next to an icon or a muted "Edited" badge that is a separate element. Set the capitalization context to standalone.
- Full sentence. Give translators one string with a named placeholder, such as
Next sync {relativeTime}, and a comment that the placeholder is a relative phrase like "in 5 minutes" or "tomorrow". Format the phrase with a middle-of-sentence capitalization context. Translators can move the placeholder, as the Japanese case requires. - No split keys. Do not store "Next sync" and "in 5 minutes" as two keys and join them in code.
On Apple platforms that context is formattingContext or capitalizationContext. On Android, use the getInstance overload that accepts a capitalization context. On the web, Intl.RelativeTimeFormat has no capitalization option, so keep phrases standalone or let the translated sentence control the case of the surrounding words.
Keep the label live and the value exact
Treat a relative label as a rendering of an absolute instant, and keep the instant as the data.
- Store and send absolute timestamps. The Authon write-up on time-ago labels puts it plainly: never serialize a relative time, and store UTC. If a server caches "5 minutes ago" in a push payload or an API response, it is wrong by the time anyone reads it, and it is in one language.
- Refresh on a cadence tied to the unit. Minute labels need about a minute; hour labels can wait longer. Refresh again on foreground, time-zone change, and language change. Our guide to applying in-app language changes lists relative times among the labels to rebuild.
- Render on the client when servers and users differ. A 2026 issue in the staaash project reports React hydration errors when a UTC server and a browser in another zone rendered different date and relative-time text (staaash issue 337). Render the absolute timestamp on the server and compute the relative phrase on the client.
- Keep the exact time available. Offer the absolute date and time in a tooltip, long-press, or accessibility value so a screen reader user can get more than "yesterday".
- Two units. Relative formatters handle one unit. If you must say "in 2 hours and 15 minutes", that is duration formatting, as an answer told a developer trying to force it through
Intl.RelativeTimeFormat(two-unit relative time question). Prefer one rounded unit in feeds.
Test relative time before release
Write tests against a fixed clock and a fixed time zone. Then vary locale, time zone, and the gap.
Locales: en, de, ja, ar, ru, pl
Zones: UTC, America/Los_Angeles, Asia/Tokyo
Gaps: 0 s, 59 s, 60 s, 59 min, 60 min,
23:50 -> 00:10 next day, 40 h, 6 days 23 h, 7 days
Contexts: standalone label, placeholder in sentence start,
placeholder mid-sentence
Checks: named vs numeric phrase, plural form, capitalization,
no English fragments, absolute date after cutoff,
exact timestamp in accessibility value
Pair the automated checks with screenshots in Arabic and German, since right-to-left layout and long German phrases are where truncation and capitalization slips show up. Compare the same timestamp across iOS, Android, and web builds; the three should agree on the unit and the day boundary even if the exact wording differs.
Also scan the string catalog. Keys like ago, just_now, minutes_ago, or yesterday usually mean a hand-built helper survived somewhere. Each one is a candidate for deletion once the formatter owns the phrase.
Where translation fits
Formatting relative time is platform code. What remains for translators is the surrounding sentence: "Edited {relativeTime}", "Next sync {relativeTime}", "Last seen {relativeTime}". Those strings need a placeholder that translators can move, a comment describing what the placeholder holds, and plural-aware review when the sentence also contains a count. That split is useful when you run strings through a translation workflow, whether human, AI-assisted with a tool such as i18nAgent, or both: translators work on the sentence and its placeholder, and the platform formatter supplies the relative phrase at runtime.
Next step
Search your codebase and string catalogs for ago, just now, yesterday, and custom time-ago helpers. Replace the first one you find with platform relative time formatting, pass the resolved app locale explicitly, choose its unit with the calendar-day rule above, and add the six-locale midnight test to your suite before the next release.
