parse static method
Constructs a new DateTime instance based on formattedString
.
Throws a FormatException if the input cannot be parsed.
Implementation
static NepaliDateTime parse(String formattedString) {
final re = _parseFormat;
final Match? match = re.firstMatch(formattedString);
if (match != null) {
int parseIntOrZero(String? matched) {
if (matched == null) return 0;
return int.parse(matched);
}
// Parses fractional second digits of '.(\d+)' into the combined
// microseconds. We only use the first 6 digits because of DateTime
// precision of 999 milliseconds and 999 microseconds.
int parseMilliAndMicroseconds(String? matched) {
if (matched == null) return 0;
final length = matched.length;
assert(length >= 1, 'matched string is empty');
var result = 0;
for (var i = 0; i < 6; i++) {
result *= 10;
if (i < matched.length) {
result += matched.codeUnitAt(i) ^ 0x30;
}
}
return result;
}
final years = int.parse(match[1]!);
final month = int.parse(match[2]!);
final day = int.parse(match[3]!);
final hour = parseIntOrZero(match[4]);
final minute = parseIntOrZero(match[5]);
final second = parseIntOrZero(match[6]);
final milliAndMicroseconds = parseMilliAndMicroseconds(match[7]);
final millisecond =
milliAndMicroseconds ~/ Duration.microsecondsPerMillisecond;
final microsecond =
milliAndMicroseconds.remainder(Duration.microsecondsPerMillisecond);
return NepaliDateTime(
years,
month,
day,
hour,
minute,
second,
millisecond,
microsecond,
);
} else {
throw FormatException('Invalid NepaliDateTime format', formattedString);
}
}