Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active February 15, 2024 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PlugFox/339bcd8dbec29a56fd53f8e0656e4a54 to your computer and use it in GitHub Desktop.
Save PlugFox/339bcd8dbec29a56fd53f8e0656e4a54 to your computer and use it in GitHub Desktop.
Date time parse and format as ISO-8601 with local timezone
/*
* 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