I want to format my DateTime.now() to March 19, 2024 at 11:06:32 AM UTC+5" but its Data type should be DateTime.
I am getting Date in that format but it is in String:
String formattedDate = DateFormat("MMMM dd, yyyy 'at' hh:mm:ss a 'UTC+5'").format(DateTime.now().toUtc().add(Duration(hours: 5)));
So, i want that String in DateTime Data Type which i am unable to do.
2
Answers
You can generalize and use
'UTC'Z
instead of'UTC+5'
, and for ease of use define your format as a variableNow you need to use the
DateFormat.parse()
methodI’m not aware of any built-in way to print UTC offsets nicely, so I think you’ll have to format
DateTime.timeZoneOffset
manually:The
formatWithOffset
implementation could be simplified by removing the different formatting cases (currently it handles time zone offsets of zero, time zone offsets with a whole number of hours, and time zone offsets with a non-zero minute component differently).Note that if you want to handle
DateTime
objects in a time zone other than the local time zone, you probably should be usingTZDateTime
objects frompackage:timezone
instead.