【发布时间】:2020-11-28 16:53:02
【问题描述】:
我有一个格式为 Month-Day-4DigitYear 的字符串日期,我想在 Flutter 中将其转换为 DateTime。我是新手编码员,我很难理解api.flutter.dev Parse method example.
下面是例子。我只是有几个问题。当我刚刚创建一个类并放入此函数时,Android Studio 会引发多个错误。我想我理解不可为空的问题,所以我删除了!和 ?到处都是标记。
我的问题是:_parseFormat、_brokenDownDateToValue、_withValue 是什么?
All 都给出错误,只声明前两个并删除 _withValue 似乎并没有解决问题,尽管删除了所有错误。就好像他们遗漏了我遗漏的关键部分,或者我需要导入一个我和 Android Studio 都不知道的包。任何人都可以解密这个吗?我对 Flutter 的文档感到非常沮丧,因为它似乎总是提供 80% 的所需信息,假设你已经对除了他们正在讨论的这个单一主题之外的所有其他主题有洞察力。在阅读手册之前必须成为专业人士。
// TODO(lrn): restrict incorrect values like 2003-02-29T50:70:80.
// Or not, that may be a breaking change.
static DateTime parse(String formattedString) {
var re = _parseFormat;
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;
int length = matched.length;
assert(length >= 1);
int result = 0;
for (int i = 0; i < 6; i++) {
result *= 10;
if (i < matched.length) {
result += matched.codeUnitAt(i) ^ 0x30;
}
}
return result;
}
int years = int.parse(match[1]!);
int month = int.parse(match[2]!);
int day = int.parse(match[3]!);
int hour = parseIntOrZero(match[4]);
int minute = parseIntOrZero(match[5]);
int second = parseIntOrZero(match[6]);
int milliAndMicroseconds = parseMilliAndMicroseconds(match[7]);
int millisecond =
milliAndMicroseconds ~/ Duration.microsecondsPerMillisecond;
int microsecond = milliAndMicroseconds
.remainder(Duration.microsecondsPerMillisecond) as int;
bool isUtc = false;
if (match[8] != null) {
// timezone part
isUtc = true;
String? tzSign = match[9];
if (tzSign != null) {
// timezone other than 'Z' and 'z'.
int sign = (tzSign == '-') ? -1 : 1;
int hourDifference = int.parse(match[10]!);
int minuteDifference = parseIntOrZero(match[11]);
minuteDifference += 60 * hourDifference;
minute -= sign * minuteDifference;
}
}
int? value = _brokenDownDateToValue(years, month, day, hour, minute,
second, millisecond, microsecond, isUtc);
if (value == null) {
throw FormatException("Time out of range", formattedString);
}
return DateTime._withValue(value, isUtc: isUtc);
} else {
throw FormatException("Invalid date format", formattedString);
}
}
【问题讨论】:
-
想指出stackoverflow.com/questions/59877288/… 以一种非常简单的方式满足了我的最终需求。但是,我仍然想尝试了解我上面缺少的内容。