无法在 dart 中使用 intl 的 DateFormat 解析 yyyyMMdd

Unable to parse yyyyMMdd with DateFormat of intl in dart

我有一个日期字符串,如“20200814”,表示 2020 年 08 月 14 日。

在 intl 的文档中是这样说的:

'yyyy.MM.dd G 'at' HH:mm:ss vvvv' 1996.07.10 AD at 15:08:56 Pacific Time

所以如果我使用这个:

DateFormat('yyyyMMdd').parse('20200814')

它必须有效,但抛出此错误:

════════ Exception caught by animation library ═════════════════════════════════
The following FormatException was thrown while notifying status listeners for AnimationController:
Trying to read MM from 20200814 at position 8

When the exception was thrown, this was the stack
#0      _DateFormatField.throwFormatException 
package:intl/…/intl/date_format_field.dart:87
#1      _DateFormatPatternField.parseField 
package:intl/…/intl/date_format_field.dart:337
#2      _DateFormatPatternField.parse 
package:intl/…/intl/date_format_field.dart:250```

我查看了 intl 源代码,不幸的是,该库不支持解析包含未被 non-numeric 个字符分隔的数字组件的日期字符串。

原因是 parse(input) 将输入字符串转换为流,当它尝试提取年份值时,它会调用 _Stream 实例方法 _Stream.nextInteger()输入流,然后消耗整个字符串,因为整个字符串可以作为单个整数读取。这会在流中留下任何要解析为月份或日期的内容,这就是引发错误的原因。

@Michael Horn 所述,package:intlDateFormat 库不支持解析日期字符串,除非它们是字符分隔的。

在这种情况下,解析器将所有输入的数字视为年份,因此在尝试根据模式查找月份时发生错误。

所以我们必须在输入之间放置一些分隔符。

String input = '20210701';
/// convert 20210701 to 2021/07/01
String newInput = '${input.substring(0, 4)}/${input.substring(4, 6)}/${input.substring(6, 8)}';
DateTime date = DateFormat('yyyy/MM/dd').parse(newInput);