Skip to content

parseTimeWithPattern

parseTimeWithPattern(value: string, pattern: string, locale?: string | string[]): string

Parse a time string against a caller-supplied token pattern (e.g. "HH:mm:ss", "h:mm a") and return it as an ISO PlainTime string.

  • Decoding, not display. This is for consuming a known, fixed producer format — a CSV column, a legacy API field, a partially-typed form value — not for generating locale-correct output. For display, use formatTime/formatDateToParts, which order fields per locale instead of hard-coding a field order (a token formatter, the inverse of this function, is deliberately out of scope for GMT).

  • pattern accepts only time-shaped tokens. A pattern containing a date-only token (y M d E G) is malformed for this function and returns "" — use parseDateTimeWithPattern for combined input. ### Token table

    TokenFieldWidthRangeNotes
    HHhour (24h)2 digits00–23
    Hhour (24h)1-2 digits0–23
    hhhour (12h)2 digits01–12needs a to resolve to 24h — see below
    hhour (12h)1-2 digits1–12same
    mmminute2 digits00–59
    mminute1-2 digits0–59
    sssecond2 digits00–59
    ssecond1-2 digits0–59
    SSSmillisecond3 digits000–999
    ameridiemlocale—getLocaleMeridiems(locale) → [AM-label, PM-label]
  • Literal text follows the Unicode UTS #35 date format pattern rules. Text in 'single quotes' is a literal, letters included. Two adjacent quotes '' are one literal ', inside or outside quoted text: "HH''mm" reads "14'30", and "'o''clock'" reads "o'clock". A quote that never closes makes the pattern malformed (""). Any other character that is not a letter (: , space, digits and so on) is a literal with no quoting.

  • a is locale-aware. If locale is omitted and the pattern uses a, GMT defaults to "en-US" rather than returning "" for every caller who didn’t have another locale in mind.

  • h/hh resolve to 24-hour using a matched a token: if the label is the PM label and hour !== 12, add 12; if the AM label and hour === 12, set hour to 0. With no a token in the pattern at all, the pattern is still valid but the hour stays ambiguous — GMT resolves it as if AM had matched (12 → 0, otherwise unchanged).

  • A shape-valid match does not by itself prove a real time: extracted fields are always handed to Temporal.PlainTime.from(fields, { overflow: "reject" }) — the regex only proves the shape, Temporal proves the time is real.

ParameterTypeDescription
valuestringThe string to decode (e.g. “02:30:45 PM”)
patternstringThe token pattern describing value’s shape (e.g. “hh:mm:ss a”)
localestring | string[]Optional BCP 47 locale tag, or a preference list of tags, for the meridiem token (default “en-US”)

ISO PlainTime string, or "" on no match, malformed pattern, or invalid input

import { parseTimeWithPattern } from "@northguild/gmt/plain/parse";
parseTimeWithPattern("14:30:45", "HH:mm:ss") // "14:30:45"
output 

plain/parse/parseTimeWithPattern.ts