toInstant method

Instant toInstant()

Converts a FhirDateTime to an Instant using the FHIR date time pattern. The upstream implementation of FhirInstant is very forgiving and will add missing time components to the timestamp.

Throws a FormatException if:

  • The input string doesn't match any of the expected formats
  • The timestamp doesn't include a time zone specification

Implementation

Instant toInstant() {
  // try with milliseconds first
  try {
    final pattern = OffsetDateTimePattern.createWithInvariantCulture(
      "uuuu-MM-dd'T'HH:mm:ss.FFFFFFo<G>",
    );

    final offsetDateTime = pattern.parse(toString()).value;
    return offsetDateTime.toInstant();
  } catch (e) {
    // try with seconds only
    try {
      final pattern = OffsetDateTimePattern.createWithInvariantCulture(
        "uuuu-MM-dd'T'HH:mm:sso<G>",
      );

      final offsetDateTime = pattern.parse(toString()).value;
      return offsetDateTime.toInstant();
    } catch (e) {
      if (e is FormatException) {
        rethrow;
      }
      throw FormatException(
        'Failed to parse "$valueString". Input must include a valid time zone specification and match one of the supported formats.',
      );
    }
  }
}