Last active
March 23, 2021 10:13
-
-
Save tcd93/851d5be213d3ca0999561ec370a320b0 to your computer and use it in GitHub Desktop.
datetime.parse2
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
void main() { | |
var s = 'Thu Jan 32 23:39:59 2021+444'; | |
var t = parse2(s); | |
print(t); | |
} | |
DateTime parse2(String formattedString) { | |
final re = RegExp(r'^(\w{3}) ' // weekday | |
r'(\w{3}) ' // month | |
r'(\d{2}) ' // day in month | |
r'(\d{2}):(\d{2}):(\d{2}) ' //hh:mm:ss | |
r'(\d{4})' // year | |
r'(\+(\d+))?$' // millisec | |
); | |
final match = re.firstMatch(formattedString); | |
if (match != null) { | |
return DateTime( | |
int.tryParse(match[7].toString()) ?? 0, | |
fromMMMtoMM(match[2].toString()), | |
int.tryParse(match[3].toString()) ?? 0, | |
int.tryParse(match[4].toString()) ?? 0, | |
int.tryParse(match[5].toString()) ?? 0, | |
int.tryParse(match[6].toString()) ?? 0, | |
int.tryParse(match[9].toString()) ?? 0 | |
); | |
} else { | |
throw FormatException('Invalid date format', formattedString); | |
} | |
} | |
int fromMMMtoMM(String mmm) { | |
switch (mmm.toLowerCase()) { | |
case 'jan': | |
return 01; | |
case 'feb': | |
return 02; | |
case 'mar': | |
return 03; | |
case 'apr': | |
return 04; | |
case 'may': | |
return 05; | |
case 'jun': | |
return 06; | |
case 'jul': | |
return 07; | |
case 'aug': | |
return 08; | |
case 'sep': | |
return 09; | |
case 'oct': | |
return 10; | |
case 'nov': | |
return 11; | |
case 'dec': | |
return 12; | |
} | |
throw FormatException('Invalid month format', mmm); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment