Last active
September 6, 2024 15:36
-
-
Save PlugFox/9364d6a88d0baf1284e4cdc0581957e7 to your computer and use it in GitHub Desktop.
Format input date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Format input date | |
* https://gist.github.com/PlugFox/9364d6a88d0baf1284e4cdc0581957e7 | |
* https://dartpad.dev/9364d6a88d0baf1284e4cdc0581957e7 | |
* Matiunin Mikhail <[email protected]>, 27 January 2023 | |
*/ | |
void main() => [ | |
'', | |
'.', | |
'..', | |
'1.2', | |
'.3.', | |
'4.5.6', | |
'0.3.4000', | |
'32.14.1995', | |
'12.11.2003', | |
].map(formatDate).forEach(print); | |
String formatDate( | |
String input, { | |
int minYear = 1970, | |
int maxYear = 3000, | |
}) { | |
final l = <int>[ | |
...input.split('.') | |
.map<int?>(int.tryParse) | |
.map<int>((i) => i ?? 1), | |
...const <int>[1,1], | |
]; | |
final y = l[2].clamp(minYear, maxYear), | |
m = l[1].clamp(1, 12), | |
d = l[0].clamp(1, DateTime(y, m + 1, 0).day); | |
String pad(int v, int w) => v.toString().padLeft(w, '0'); | |
return '${pad(d, 2)}' | |
'.' | |
'${pad(m, 2)}' | |
'.' | |
'${pad(y, 4)}'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment