# FormatException：解析日期字符串时出现意外字符（位于字符 N 处）

- **ID:** `flutter/dart-format-exception`
- **领域:** flutter
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

由 intl 或其它包解析的日期字符串与预期的格式模式不匹配，通常是由于区域设置差异或输入格式错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Flutter 3.13.0 | active | — | — |
| Dart 3.1.0 | active | — | — |
| intl 0.18.1 | active | — | — |

## 解决方案

1. ```
   Validate and sanitize the date string before parsing. Example: String cleaned = dateString.replaceAll(RegExp(r'[^0-9:/\- ]'), ''); DateTime parsed = DateFormat('yyyy-MM-dd HH:mm:ss').parse(cleaned);
   ```
2. ```
   Use a flexible parser like DateTime.tryParse() or the intl package's DateFormat with multiple patterns. Example: DateTime? date = DateFormat('yyyy-MM-dd').tryParse(input) ?? DateFormat('MM/dd/yyyy').tryParse(input);
   ```
3. ```
   Log the exact input string and expected format to debug the mismatch. Add a debug print: print('Parsing date: $input with format $pattern');
   ```

## 无效尝试

- **Change the date format pattern randomly until it works** — Without understanding the input format, random changes are unlikely to match the actual string. (90% 失败率)
- **Use try-catch to swallow the exception** — Silencing the error does not fix the underlying data issue and may lead to silent failures. (80% 失败率)
