Last active
February 15, 2024 13:04
-
-
Save PlugFox/339bcd8dbec29a56fd53f8e0656e4a54 to your computer and use it in GitHub Desktop.
Date time parse and format as ISO-8601 with local timezone
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
/* | |
* Date time parse and format as ISO-8601 with local timezone | |
* https://gist.github.com/PlugFox/339bcd8dbec29a56fd53f8e0656e4a54 | |
* https://dartpad.dev/339bcd8dbec29a56fd53f8e0656e4a54?id=&null_safety=true | |
*/ | |
import 'dart:async'; | |
import 'package:intl/intl.dart' as intl; | |
const String source = '2021-01-02T03:08:04+02:30'; | |
void main() => runZonedGuarded<void>( | |
() async { | |
final dateTime = DateTime.tryParse(source); | |
if (dateTime == null) throw FormatException('Invalid date format'); | |
print(dateTime.toLocalIso8601String()); | |
}, | |
(error, stackTrace) => print('ERROR: $error'), | |
); | |
extension LocalTimeX on DateTime { | |
static final intl.DateFormat _formatter = | |
intl.DateFormat("yyyy-MM-dd'T'HH:mm:ss"); | |
String toLocalIso8601String() { | |
final dateTime = toLocal(); | |
final tz = dateTime.timeZoneOffset; | |
final buffer = StringBuffer() | |
..write(_formatter.format(dateTime)) | |
..write(tz.isNegative ? '-' : '+') | |
..write(tz.inHours.abs().toString().padLeft(2, '0')) | |
..write(':') | |
..write((tz.inMinutes.abs() % 60).toString().padLeft(2, '0')); | |
return buffer.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment