fix: handle datetime outside the valid range supported by dart (#21526)

* fix: handle datetime outside the valid range supported by dart

* add tests for tryFromSecondsSinceEpoch

---------

Co-authored-by: shenlong-tanwen <139912620+shalong-tanwen@users.noreply.github.com>
This commit is contained in:
shenlong 2025-09-03 00:50:49 +05:30 committed by GitHub
parent 873f7921da
commit ec2f94cae8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 81 additions and 3 deletions

View file

@ -0,0 +1,19 @@
const int _maxMillisecondsSinceEpoch = 8640000000000000; // 275760-09-13
const int _minMillisecondsSinceEpoch = -62135596800000; // 0001-01-01
DateTime? tryFromSecondsSinceEpoch(int? secondsSinceEpoch) {
if (secondsSinceEpoch == null) {
return null;
}
final milliSeconds = secondsSinceEpoch * 1000;
if (milliSeconds < _minMillisecondsSinceEpoch || milliSeconds > _maxMillisecondsSinceEpoch) {
return null;
}
try {
return DateTime.fromMillisecondsSinceEpoch(milliSeconds);
} catch (e) {
return null;
}
}