# Healthcare: Clinical Timestamps

Industry: Healthcare

HL7 International calls HL7 version 2 "one of the most widely implemented standards for
healthcare information in the world"
([HL7 product list](https://tscwiki.hl7.org/TSC_Product_List_V2)). The date-time in a version 2
message is not ISO 8601. The number of digits says how precise the value is, and the offset is
optional. A reader that takes a value without an offset for UTC moves every event by the offset
of the place that sent it, and a reader that pads a year to a moment states a fact nobody sent.

FHIR R4 is the other standard a clinical system meets. Its `date`, `dateTime` and `instant` are
profiles of ISO 8601, and they differ from HL7 version 2 on the point that matters most: a FHIR
time must carry a zone, so there is no sender's local time to guess.

There are three functions for each standard. For HL7, `parseHL7` reads a value, `formatHL7`
writes one and `isValidHL7` checks one. For FHIR, `parseFHIR`, `formatFHIR` and `isValidFHIR` do
the same. Each takes a string and returns a string, an object or a boolean, and none of them
throws. A call the types accept returns the sentinel (`null`, `""` or `false`) when the value is
wrong. The HL7 sections come first, and [FHIR R4](#fhir-r4-date-datetime-and-instant) follows
them.

```typescript
import { parseHL7 } from "@northguild/gmt/healthcare/parse";
import { formatHL7 } from "@northguild/gmt/healthcare/format";
import { isValidHL7 } from "@northguild/gmt/healthcare/validate";
```

Each function has a page in the [healthcare reference](/gmt/reference/healthcare/parse/), with a
playground that runs it.

## HL7 version 2: DTM and TS

The standard names two types. `DTM` is the date-time. `TS` is the older time stamp, a `DTM`
followed by a degree of precision. The degree is kept only for backward compatibility, and
version 2.6 withdrew `TS`. HL7's own chapters call them 2.A.22 and 2.A.77, and the degree 2.A.77.2
(headed 2.A.1.22, 2.A.1.77 and 2.A.1.77.2 in the hl7.eu copy of version 2.5.1).

### The four kinds

`parseHL7` returns one of four kinds, or `null` for a value it does not read.

| Kind        | When                                    | Members                                  |
| ----------- | --------------------------------------- | ---------------------------------------- |
| `"instant"` | a minute or finer, with an offset       | `instant`, `offset`, `local`, `precision` |
| `"local"`   | a minute or finer, no offset            | `local`, `precision`                     |
| `"partial"` | year, month, day or hour, or cut to one by a `TS` degree | `local`, `offset`, `precision` |
| `"null"`    | the null value `""`                     | none                                     |

```typescript
import { parseHL7 } from "@northguild/gmt/healthcare/parse";

parseHL7("20240615103000+0300");
// { kind: "instant", instant: "2024-06-15T07:30:00Z", offset: "+03:00",
//   local: "2024-06-15T10:30:00", precision: "second" }
parseHL7("20240615103000");
// { kind: "local", local: "2024-06-15T10:30:00", precision: "second" }
parseHL7("20240615");
// { kind: "partial", local: "2024-06-15", offset: "", precision: "day" }
parseHL7('""');
// { kind: "null" }
parseHL7("2024-06-15");
// null
```

The type makes you check `kind` before you read `instant`. Only the `"instant"` kind has one.

### Precision is the number of digits

The picture in 2.A.22 is `YYYY[MM[DD[HH[MM[SS[.S[S[S[S]]]]]]]]][+/-ZZZZ]`, and the standard says
"The number of characters populated (excluding the time zone specification) specifies the
precision". The digits sent are the precision.

| Digits sent            | Precision    |
| ---------------------- | ------------ |
| 4                      | `"year"`     |
| 6                      | `"month"`    |
| 8                      | `"day"`      |
| 10                     | `"hour"`     |
| 12                     | `"minute"`   |
| 14                     | `"second"`   |
| 14, a point, 1 to 4    | `"fraction"` |

`local` is written at the precision sent, so an hour is `2024-06-15T10` and no minute is added.
From the minute on, seconds are always written, so a minute reads as `10:30:00`. At most four
fraction digits are read, and the fraction is kept as it was sent.

```typescript
parseHL7("2024061510");
// { kind: "partial", local: "2024-06-15T10", offset: "", precision: "hour" }
parseHL7("202406151030");
// { kind: "local", local: "2024-06-15T10:30:00", precision: "minute" }
parseHL7("20240615103000.1234");
// { kind: "local", local: "2024-06-15T10:30:00.1234", precision: "fraction" }
parseHL7("20240615103000.12345");
// null
```

### The offset that is not there

2.A.22 says "if the time zone is not included, the time zone defaults to that of the local time
zone of the sender". A value with no offset is the sender's local time, so the `"local"` kind
has no instant. Appending `Z` would state a place the message never named.

An offset is `+` or `-` and four digits. `+0000` and `-0000` both mean UTC and both read as
`+00:00`. The standard restricts offsets to "legally-defined time zones" but names no list, so
any hour from `00` to `23` and minute from `00` to `59` is read.

```typescript
parseHL7("20240615103000+0000");
// { kind: "instant", instant: "2024-06-15T10:30:00Z", offset: "+00:00",
//   local: "2024-06-15T10:30:00", precision: "second" }
parseHL7("20240615103000-0000");
// { kind: "instant", instant: "2024-06-15T10:30:00Z", offset: "+00:00",
//   local: "2024-06-15T10:30:00", precision: "second" }
parseHL7("20240615103000+0530");
// { kind: "instant", instant: "2024-06-15T05:00:00Z", offset: "+05:30",
//   local: "2024-06-15T10:30:00", precision: "second" }
```

### From a local time to an instant

When the message names no offset, you know the zone and GMT does not. Pass the `local` member and
the sending facility's IANA zone to `resolveLocal`:

```typescript
import { parseHL7 } from "@northguild/gmt/healthcare/parse";
import { resolveLocal } from "@northguild/gmt/instant/convert";

const result = parseHL7("20240615103000");
if (result?.kind === "local") {
  resolveLocal(result.local, "Europe/Helsinki"); // "2024-06-15T07:30:00Z"
}
```

A wall time can fall in an hour the zone skips or repeats. `resolveLocal` takes a
`disambiguation` option for those, and its [reference page](/gmt/reference/instant/convert/resolveLocal/)
says what each value does. `"reject"` returns `""` instead of choosing:

```typescript
resolveLocal("2024-03-31T03:30:00", "Europe/Helsinki"); // "2024-03-31T01:30:00Z" — 03:30 was skipped; the default, "compatible", takes the later reading
resolveLocal("2024-03-31T03:30:00", "Europe/Helsinki", { disambiguation: "reject" }); // ""
resolveLocal("2024-10-27T03:30:00", "Europe/Helsinki"); // "2024-10-27T00:30:00Z" — 03:30 happened twice; "compatible" takes the earlier reading
resolveLocal("2024-10-27T03:30:00", "Europe/Helsinki", { disambiguation: "later" }); // "2024-10-27T01:30:00Z" — 03:30 happened twice
resolveLocal("2024-10-27T03:30:00", "Europe/Helsinki", { disambiguation: "reject" }); // ""
```

### A partial value names a span

`1965` is a birth year. It is not 1 January 1965 at midnight, and padding it to a moment states a
fact the sender did not send. A `"partial"` value keeps its precision and has no instant. It keeps
an offset when one was sent with it.

```typescript
parseHL7("1965");
// { kind: "partial", local: "1965", offset: "", precision: "year" }
parseHL7("196506");
// { kind: "partial", local: "1965-06", offset: "", precision: "month" }
parseHL7("20240615-0500");
// { kind: "partial", local: "2024-06-15", offset: "-05:00", precision: "day" }
```

### `TS` and its degree of precision

A `TS` is a `DTM`, then `^`, then one of `Y L D H M S` (year, month, day, hour, minute, second).
The degree only lowers the precision. 2.A.77.2 says it "is either the same as or overrides the
precision indicated by the first component. It may not indicate greater precision".

```typescript
parseHL7("199904011200^L");
// { kind: "partial", local: "1999-04", offset: "", precision: "month" } — April 1999
parseHL7("20240615103000.1234^S");
// { kind: "local", local: "2024-06-15T10:30:00", precision: "second" } — the fraction is cut
parseHL7("20240615^S");
// null — a second is finer than the day sent
parseHL7("20240615^");
// { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } — an empty degree is absent
parseHL7("20240615^D^");
// { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } — so is an empty third component
```

A field read on its own carries no MSH-2, so `parseHL7` takes the separators Figure 2-1
recommends: `^` between components and `&` between subcomponents (ch. 2 §2.5.4). A feed whose
MSH-2 names others re-joins the field with `^` and `&` before it calls `parseHL7`.

A receiver ignores "components, subcomponents, and extra repetitions of a field that are present
but were not expected" (ch. 2 §2.6.2), and a later version of HL7 adds components at the end of a
data type (§2.8.1, §2.8.2). So a third component, and anything after it, is not read, unless it
holds a `|`, a `~` or a control character: those end the field, the repetition or the segment, so
the text is not one field and `parseHL7` returns `null`. GMT reads the first two components more
strictly than §2.6.2 asks: each is exactly one value, so a `&` inside the date-time or the degree
returns `null`. A component left empty is not present, so an empty `DTM` returns `null`.

```typescript
parseHL7("20240615^D^X");
// { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } — the third component is ignored
parseHL7("20240615^D^X&Y");
// { kind: "partial", local: "2024-06-15", offset: "", precision: "day" } — a & in an ignored component is ignored too
parseHL7("2024&X");
// null — a subcomponent inside the date-time
parseHL7("20240615^D^X|Y");
// null — a | ends the field, so this is more than one field
```

### Midnight is the start of the day

2.A.22 gives `198807050000` as "Midnight of the night extending from July 4 to July 5, 1988", so
`0000` is the start of the stated day. Hour `24` and second `60` are refused.

```typescript
parseHL7("198807050000");
// { kind: "local", local: "1988-07-05T00:00:00", precision: "minute" }
parseHL7("2024061524");
// null
parseHL7("20240615103060");
// null
```

### The null value

A field that holds two double quotes (`""`) is the null value. It clears a stored value, and
chapter 2 says it "is different from omitting an optional data field". `parseHL7` returns it as
its own kind. An empty string is not the null value and returns `null`. Never treat one as the
other.

```typescript
parseHL7('""'); // { kind: "null" }
parseHL7(""); // null
```

### Writing a `DTM`

`formatHL7` takes an ISO 8601 value and writes a `DTM`. It writes the offset the value has, and
`Z` writes `+0000`. It never writes a `TS`. The precision is the one the input is written in, and
the `precision` option only lowers it. It cuts and never rounds, so a fraction of `.98765` is
written as `.9876`.

```typescript
import { formatHL7 } from "@northguild/gmt/healthcare/format";

formatHL7("2024-06-15T10:30:00"); // "20240615103000"
formatHL7("2024-06-15T10:30"); // "202406151030"
formatHL7("2024-06-15T10:30:00Z"); // "20240615103000+0000"
formatHL7("2024-06-15T10:30:45.98765-05:00"); // "20240615103045.9876-0500"
formatHL7("2024-06-15T10:30:45.5Z", { precision: "minute" }); // "202406151030+0000"
```

A `"local"` value read at minute precision comes back from `parseHL7` with `:00` seconds, so
writing it with the digits it was sent with takes the precision `parseHL7` returned. A
`"partial"` value with an offset has no ISO input form, because `2024-06-15-05:00` is not ISO
8601. Write it from the instant, at the precision you want:

```typescript
const r = parseHL7("202406151030");
if (r?.kind === "local") {
  formatHL7(r.local); // "20240615103000" — seconds added
  formatHL7(r.local, { precision: r.precision }); // "202406151030" — the digits sent
}
formatHL7("2024-06-15T10:30:00-05:00", { precision: "day" }); // "20240615-0500"
formatHL7("2024-06-15-05:00"); // "" — not ISO 8601
```

`formatHL7` returns `""` when it cannot write the value without changing it: an offset with
seconds, a year outside 0000–9999, a reduced ISO form with an offset, an annotation of any kind (a time
zone is not read: write the wall clock with its offset) and a precision finer than the input.

```typescript
formatHL7("2024-06-15T10:30:00+05:30:15"); // "" — the offset has seconds
formatHL7("+010000-01-01T00:00:00"); // "" — the year is outside 0000–9999
formatHL7("2024-06-15T10:30:00Z[Europe/Helsinki]"); // "" — an annotation is not read
formatHL7("2024-06-15T10:30:00", { precision: "fraction" }); // "" — there is no fraction to write
```

### Check before reading

`isValidHL7` is `parseHL7(value) !== null`, so the two cannot disagree. The null value is valid.

```typescript
import { isValidHL7 } from "@northguild/gmt/healthcare/validate";

isValidHL7("20240615103000"); // true
isValidHL7("199904011200^L"); // true
isValidHL7('""'); // true
isValidHL7(""); // false
isValidHL7("20240615^S"); // false
```

### What is not read

These return `null` from `parseHL7` and `false` from `isValidHL7`: a separator other than `^`
and `&`, an empty `DTM`, a lower-case degree, a leap second, more than four fraction digits and
ISO 8601 extended form (`2024-06-15T10:30:00`).

```typescript
parseHL7("20240615~D"); // null
parseHL7("^D"); // null — the DTM is empty
parseHL7("20240615^l"); // null
parseHL7("2024-06-15T10:30:00"); // null — ISO 8601 is the input of formatHL7
```

### The exported types

[`Hl7DateTime`](/gmt/reference/healthcare/parse/parseHL7/#hl7datetime) is the result of `parseHL7`.
Its `precision` is an [`Hl7PartialPrecision`](/gmt/reference/types/Hl7PartialPrecision/), year to
hour, for a `"partial"` value and an [`Hl7MomentPrecision`](/gmt/reference/types/Hl7MomentPrecision/),
minute to fraction, for an `"instant"` or `"local"` one.
[`Hl7Precision`](/gmt/reference/healthcare/format/formatHL7/#hl7precision) is the two together, and
[`Hl7FormatOptions`](/gmt/reference/healthcare/format/formatHL7/#hl7formatoptions) is the options of
`formatHL7`.

## FHIR R4: date, dateTime and instant

FHIR R4 Datatypes §2.24.0.1 defines three primitive types that carry a date. HL7 publishes one
regular expression for each in the R4 StructureDefinitions, and GMT exposes them as `fhirDate`,
`fhirDateTime` and `fhirInstant` in `@northguild/gmt/regex`. The notes in §2.24.0.1 call them
"informative, not normative", so they are a first filter and not a check.

```typescript
import { parseFHIR } from "@northguild/gmt/healthcare/parse";
import { formatFHIR } from "@northguild/gmt/healthcare/format";
import { isValidFHIR } from "@northguild/gmt/healthcare/validate";
```

### Three types, one grammar

`parseFHIR` reads a value of any of the three types and returns the value as sent, its precision
and its offset. `isValidFHIR` and `formatFHIR` take the type as their second argument, because the
type decides which precisions are allowed.

| Precision    | Example                     | Allowed in            |
| ------------ | --------------------------- | --------------------- |
| `"year"`     | `2024`                      | `date`, `dateTime`    |
| `"month"`    | `2024-06`                   | `date`, `dateTime`    |
| `"day"`      | `2024-06-15`                | `date`, `dateTime`    |
| `"second"`   | `2015-02-07T13:28:17-05:00` | `dateTime`, `instant` |
| `"fraction"` | `2015-02-07T13:28:17.239Z`  | `dateTime`, `instant` |

A `second` value is `YYYY-MM-DDThh:mm:ss` and a zone. A `fraction` value adds a decimal part to the
seconds.

```typescript
parseFHIR("2015-02-07T13:28:17-05:00");
// { value: "2015-02-07T13:28:17-05:00", precision: "second", offset: "-05:00" }
parseFHIR("2024-06-15T10:30:00.5+02:00");
// { value: "2024-06-15T10:30:00.5+02:00", precision: "fraction", offset: "+02:00" }

isValidFHIR("2024-06-15T10:30:00Z", "instant"); // true
isValidFHIR("2024-06-15", "instant"); // false — an instant is a second or finer
isValidFHIR("2024-06-15T10:30:00Z", "date"); // false — a date has no time
```

There is no hour or minute precision in FHIR: a time always carries seconds. A fraction of more
than nine digits is refused, not cut short, because Temporal holds nanoseconds.

### Precision is kept

`2024-06` is a month. It is not midnight on 1 June, and padding it states a day and a time the
sender did not send. `parseFHIR` returns the value as it was sent, with nothing added.

```typescript
parseFHIR("2024");
// { value: "2024", precision: "year", offset: "" }
parseFHIR("2024-06");
// { value: "2024-06", precision: "month", offset: "" }
parseFHIR("2024-6-15");
// null — the month is not padded
```

Comparing one partial value with another is a different problem. FHIRPath defines it in its
[Equality](https://hl7.org/fhirpath/N1/#equality) and
[Comparison](https://hl7.org/fhirpath/N1/#comparison) sections, and GMT does not compare partial
values. Use a FHIRPath engine for that, and use `parseFHIR` to read each value first.

### A time needs a zone

HL7 version 2 reads a time with no offset as the sender's local time. FHIR does not allow one:
§2.24.0.1 says that "if hours and minutes are specified, a time zone SHALL be populated". So a
FHIR time with no zone is not a local time to resolve later. It is invalid, and `parseFHIR`
returns `null` for it.

```typescript
parseFHIR("2024-06-15T10:30:00"); // null — no zone
parseFHIR("2024-06-15T10:30"); // null — no seconds, and no zone
parseFHIR("2024-06-15T24:00:00Z"); // null — 24:00 is not allowed
isValidFHIR("2024-06-15T10:30:00", "dateTime"); // false
```

The zone is `Z` or `±hh:mm` from `-14:00` to `+14:00`. `Z`, `+00:00` and `-00:00` all read as
`offset: "+00:00"`, and `value` keeps the spelling that was sent. Compare `offset`, not the
strings.

```typescript
parseFHIR("2024-06-15T10:30:00Z");
// { value: "2024-06-15T10:30:00Z", precision: "second", offset: "+00:00" }
parseFHIR("2024-06-15T10:30:00-00:00");
// { value: "2024-06-15T10:30:00-00:00", precision: "second", offset: "+00:00" }
parseFHIR("2024-06-15T10:30:00+14:30"); // null — past +14:00
```

### Leap seconds

FHIR allows a second of `60`: "Leap Seconds are allowed" in §2.24.0.1. GMT accepts it only on an
inserted leap second, at any offset spelling. `2016-12-31T23:59:60Z` was a real second, and
`2017-12-31T23:59:60Z` was not.

```typescript
isValidFHIR("2016-12-31T23:59:60Z", "instant"); // true
isValidFHIR("2017-12-31T23:59:60Z", "instant"); // false — no second was inserted that day
parseFHIR("2016-12-31T18:59:60-05:00");
// { value: "2016-12-31T18:59:60-05:00", precision: "second", offset: "-05:00" } — the same second
```

### The patterns prove shape only

`fhirDate`, `fhirDateTime` and `fhirInstant` accept strings that `isValidFHIR` refuses. A match
says the value has the right shape, not that it is a real date or a real second.

```typescript
import { fhirDateTime, fhirInstant } from "@northguild/gmt/regex";

fhirDateTime.test("2024-02-30"); // true — there is no 30 February
isValidFHIR("2024-02-30", "dateTime"); // false

fhirInstant.test("2017-12-31T23:59:60Z"); // true — a second of 60 on any day
isValidFHIR("2017-12-31T23:59:60Z", "instant"); // false

fhirInstant.test("2024-06-15T10:30:00.1234567890Z"); // true — a fraction of any length
isValidFHIR("2024-06-15T10:30:00.1234567890Z", "instant"); // false — ten digits
```

The other direction holds: a value that `isValidFHIR` accepts always matches the pattern for its
type. Use the pattern to filter, then `isValidFHIR` or `parseFHIR` to decide.

### Writing a FHIR value

`formatFHIR` takes an ISO 8601 value and writes it as a `date`, `dateTime` or `instant`. It reads
the wall clock as written, and it cuts and never rounds, so the result never names a later second,
day or month than the input. The `precision` option only lowers the precision. A finer one returns
`""`.

```typescript
formatFHIR("2024-06-15T23:59:59.999Z", "instant", { precision: "second" }); // "2024-06-15T23:59:59Z" — cut, not rounded
formatFHIR("2024-12-31T23:59:59.999-05:00", "dateTime", { precision: "year" }); // "2024"
formatFHIR("2024-06", "dateTime", { precision: "day" }); // "" — finer than the value carries
```

Under `date`, the result is the wall-clock date at the input's own offset, because FHIR forbids a
zone on a `date`. The designator is written as the input spells it, so `Z`, `+00:00` and `-00:00`
stay as they were. A second of `60` returns `""`, because §2.24.0.1 says applications producing
leap seconds "MAY choose to avoid" them.

```typescript
formatFHIR("2024-06-15T23:30:00-05:00", "date"); // "2024-06-15" — the date where the sender was
formatFHIR("2024-06-15T10:30:00-00:00", "dateTime"); // "2024-06-15T10:30:00-00:00"
formatFHIR("2024-06-15T10:30:00", "instant"); // "" — an instant needs a zone
formatFHIR("2016-12-31T23:59:60Z", "instant"); // "" — a leap second is not written
```

A time zone annotation is not read: `formatFHIR("2024-06-15T23:30:00Z[Europe/Berlin]", "date")` is
`""`. Write the wall clock with its offset instead. An offset that is not a whole number of
minutes, such as `+02:00:30`, returns `""`, under `date` too.

FHIR has no minute precision, and `formatFHIR` never zero-fills. An HL7 version 2 time at minute
precision therefore gives `""` under `dateTime` and `instant`. The caller either cuts it to a day
or adds `:00` knowingly. `parseHL7` already writes `:00` into `local` for a minute value, so look
at `precision` before you join `local` and `offset`.

```typescript
import { parseHL7 } from "@northguild/gmt/healthcare/parse";
import { formatFHIR } from "@northguild/gmt/healthcare/format";

formatFHIR("2024-06-15T10:30-05:00", "dateTime"); // "" — no minute precision in FHIR
const sent = parseHL7("202406151030-0500");
if (sent?.kind === "instant" && sent.precision === "minute") {
  const iso = sent.local + sent.offset; // "2024-06-15T10:30:00-05:00": the :00 is added
  formatFHIR(iso, "dateTime", { precision: "day" }); // "2024-06-15"
  // Writing the whole value is right only if a zero second is acceptable.
  formatFHIR(iso, "dateTime"); // "2024-06-15T10:30:00-05:00"
}
```

[`FhirDateTime`](/gmt/reference/healthcare/parse/parseFHIR/#fhirdatetime) is the result of
`parseFHIR`. Its `precision` is a [`FhirPrecision`](/gmt/reference/types/FhirPrecision/).
[`FhirDateType`](/gmt/reference/types/FhirDateType/) is the second argument of `isValidFHIR` and
`formatFHIR`, and
[`FhirFormatOptions`](/gmt/reference/healthcare/format/formatFHIR/#fhirformatoptions) is the options
of `formatFHIR`.

## See it break, then work

- [An HL7 Time Read as UTC](/gmt/scenarios/an-hl7-time-read-as-utc/)
- [A TS Date Read as a Time](/gmt/scenarios/a-ts-date-read-as-a-time/)
- [A FHIR Month Padded to Midnight](/gmt/scenarios/a-fhir-month-padded-to-midnight/)
- [Healthcare mistakes](/gmt/mistakes/healthcare/), and the [FHIR R4 mistakes](/gmt/mistakes/healthcare/#fhir-r4)
- [HL7 Timestamp Reader](/gmt/tools/hl7-timestamp-reader/), a tool that reads a value of your own
- [FHIR Date Checker](/gmt/tools/fhir-date-checker/), a tool that checks a FHIR `date`, `dateTime` or `instant` of your own
