Last active
November 10, 2021 16:03
-
-
Save apgapg/84d855e41c0134a34ff8b2cf034ad249 to your computer and use it in GitHub Desktop.
Get correct ISO DateTime String with offset in Flutter: https://dartpad.dev/84d855e41c0134a34ff8b2cf034ad249
This file contains hidden or 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
import 'package:intl/intl.dart'; | |
import 'package:meta/meta.dart'; | |
void main() { | |
print(DateUtils.formatISOTime(DateTime.now())); | |
print(DateUtils.getCurrentISOTimeString()); | |
} | |
class DateUtils { | |
///Converts DateTime to ISO format | |
///Output: 2020-09-16T20:41:09.331+05:30 | |
static String formatISOTime(DateTime date) { | |
var duration = date.timeZoneOffset; | |
if (duration.isNegative) | |
return (date.toIso8601String() + | |
"-${duration.inHours.toString().padLeft(2, '0')}:${(duration.inMinutes - (duration.inHours * 60)).toString().padLeft(2, '0')}"); | |
else | |
return (date.toIso8601String() + | |
"+${duration.inHours.toString().padLeft(2, '0')}:${(duration.inMinutes - (duration.inHours * 60)).toString().padLeft(2, '0')}"); | |
} | |
///get ISO time String from DateTime | |
///Output: 2020-09-16T20:42:38.629+05:30 | |
static String getCurrentISOTimeString({DateTime dateTime}) { | |
var date = dateTime ?? DateTime.now(); | |
//Time zone may be null in dateTime hence get timezone by datetime | |
var duration = DateTime.now().timeZoneOffset; | |
if (duration.isNegative) | |
//TODO: convert duration to abs value instead of below params | |
return (date.toIso8601String() + | |
"-${duration.inHours.abs().toString().padLeft(2, '0')}:${(duration.inMinutes.abs() - (duration.inHours.abs() * 60)).toString().padLeft(2, '0')}"); | |
else | |
return (date.toIso8601String() + | |
"+${duration.inHours.toString().padLeft(2, '0')}:${(duration.inMinutes - (duration.inHours * 60)).toString().padLeft(2, '0')}"); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@loonix, the code will not have a double minus if it's using the absolute value of the duration (.abs()), but your suggestion would also work.