I'm receiving a DateTime
response from API that's sets the timezone to UTC.
But when I try to convert the received data using toLocal()
it doesn't convert.
my local time is HKT
here's my code.
//TIME DIFFERENCE getNotificationDate(DateTime date) { date = date.toUtc(); final convertedDate = date.toLocal(); final dateNow = DateTime.now(); print('TIMENOW: ' + dateNow.toString()); print('TIMENOTIFC: ' + convertedDate.toString()); final difference = dateNow.difference(convertedDate); print('DIFFERENCE: ' + difference.toString()); return getDurationFormat(difference); }
EDIT:
date
is the DateTime
I'm receiving from the API. which is in UTC timezone.
I used print('TIMEZONENAME: ' + date.timeZoneName;
and it automatically sets the timezone to HKT. that's why it does nothing when I try to use date.toLocal()
(GMT-5:00) Eastern Time (US & Canada)Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.
The ToLocalTime method converts a DateTime value from UTC to local time. To convert the time in any designated time zone to local time, use the TimeZoneInfo. ConvertTime method. The value returned by the conversion is a DateTime whose Kind property always returns Local.
Use the Date() constructor to convert UTC to local time, e.g. new Date(utcDateStr) . Passing a date and time string in ISO 8601 format to the Date() constructor converts the UTC date and time to local time. Copied!
Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.
Flutter gave us the easiest way to convert it. You just need to pass utc: true while parsing your date.
var dateTime = DateFormat("yyyy-MM-dd HH:mm:ss").parse(dateUtc, true); var dateLocal = dateTime.toLocal();
Input:
Assume my TimeZone : +05:30
UTC Date -> 2020-02-12 23:57:02.000
Output:
Local Date -> 2020-02-12 18:27:02.019660
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With