2

I have a date string like '20200814' that means day 14 of month 08 of year 2020.

In the docs of intl it said this:

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

So if I use this:

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

It must works, but throw this error:

════════ 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```
Sir Galan
  • 55
  • 5

2 Answers2

5

I've taken a look at the intl source, and unfortunately the library does not support parsing a date string containing numerical components that are not separated by non-numeric characters.

The reason for this is that parse(input) converts the input string to a stream, and when it tries to extract the year value, it calls the _Stream instance method _Stream.nextInteger() on the input stream, which then consumes the entire string, since the whole string can be read as a single integer. This leaves nothing in the stream to be parsed as month or day, which is why the error is thrown.

Michael Horn
  • 3,819
  • 9
  • 22
  • 1
    Thanks! So a solution if someone need it is to preprocess the string separating it using the number of characters needed and then join it with a character or just define a DateTime using the 3 groups extracted. – Sir Galan Sep 29 '20 at 17:56
0

As @Michael Horn mentioned, The package:intl's DateFormat library does not support parsing date strings unless they are character-delimited.

In this case, parser sees all the numbers entered as years, so it occurs an error trying to find the month according to the pattern.

So we have to put some separator between the input.

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);
UNW
  • 442
  • 4
  • 6