'DateTime in UTC not converting to Local

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()



Solution 1:[1]

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

Solution 2:[2]

To convert UTC time to local time with the specified format including date

var dateFormat = DateFormat("dd-MM-yyyy hh:mm aa"); // you can change the format here
var utcDate = dateFormat.format(DateTime.parse(uTCTime)); // pass the UTC time here
var localDate = dateFormat.parse(utcDate, true).toLocal().toString();
String createdDate = dateFormat.format(DateTime.parse(localDate)); // you will local time

As I answered here: https://stackoverflow.com/a/65690095/2462531

Solution 3:[3]

// you have time in utc
var dateUtc = DateTime.now().toUtc();
print("dateUtc: $dateUtc"); // 2019-10-10 12:05:01

// convert it to local
var dateLocal = dateUtc.toLocal();
print("local: $dateLocal"); // 2019-10-10 14:05:01

Can you see the difference in hours, in utc it is 12 and locally it is 14.

Solution 4:[4]

Firstly, convert your Sting to DateTime.

> DateTime dateTime = DateTime.parse(json['pickUpTime']);

Secondly, add timeZoneOffSet to your converted date time it will convert utc to your local time.

> dateTime = dateTime.add(DateTime.parse(json['pickUpTime']).timeZoneOffset);

Final Code

DateTime dateTime = DateTime.parse(json['pickUpTime']);
dateTime = dateTime.add(DateTime.parse(json['pickUpTime']).timeZoneOffset);

Solution 5:[5]

You can try this code:

getNotificationDate(DateTime date) {
    date = DateTime.utc(date.year,date.month,date.day,date.hour,date.minute,date.second);;
    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);
  }

Solution 6:[6]

If somebody needs to parse a UTC timestamp in isoformat, for example something like this:

>>> from datetime import datetime
>>> datetime.utcnow().format()
'2021-07-20T19:35:19.769891'

Then you can parse this and convert this to local time by

DateTime parseDatetimeFromUtc({required String isoFormattedString}){
  var dateTime = DateTime.parse(isoFormattedString + '+00:00');
  return dateTime.toLocal();
}

The '+00:00' is append here as the timezone information part which I do not send over my API to save some bytes. Maybe this helps someone who is in the same situation.

Of course you do not need this hardcoded suffix if you use a timezone aware timestamp in your backend:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2021-07-20T19:42:36.538195+00:00'

Solution 7:[7]

I've done something like this.

String dateTimeFormatter(String dateTime, {String? format}) {
  return DateFormat(format ?? 'yyyy/MM/dd, hh:mm a')
      .format(DateTime.parse(dateTime).toLocal())
      .toString();
}

just pass the format which you want to display in your app.

Solution 8:[8]

For those who parsing TimeStamp from Firestore.

*sentAt is Timestamp

String timeToDate = widget.sentAt.toDate().toString();
    var dateTime = DateFormat("yyyy-MM-dd HH:mm:ss").parse(timeToDate, true);
    var dateLocal = dateTime.toLocal();

Solution 9:[9]

Install intl package from pub.dev

add following line :

import 'package:intl/intl.dart';

You can make an extension like below so it will be very helpful and easy to use anywhere in a whole project.

//just make sure you have passed the right date format of utc("yyyy-MM-dd HH:mm:ss"). I have passed by default my format.

//for example
// 2020-11-25 24:12:36 -> "yyyy-MM-dd HH:mm:ss"
DateTime localDate=utcDateTime.toLocalDateTime();


//for different formats you can pass your own dateFormat for utcDate like below:
// 20-11-25 24:12:36 -> "yy-MM-dd HH:mm:ss"
DateTime localDate=utcDateTime.toLocalDateTime("yy-MM-dd HH:mm:ss");

extension DateTimeExtension on DateTime {
  DateTime toLocalDateTime({String format = "yyyy-MM-dd HH:mm:ss"}) {
    var dateTime = DateFormat(format).parse(this.toString(), true);
    return dateTime.toLocal();
  }
}

Solution 10:[10]

this is how i converted to my required time .which was showing as

I/flutter ( 5709): 16 Apr 08:30 PM 2021

when using the

var date=DateFormat("dd MMM hh:mm a y").format(DateTime.fromMillisecondsSinceEpoch(start*1000));
      print(date);

but after using this code i got my right time

var date=DateFormat("dd MMM hh:mm a y").format(DateTime.fromMillisecondsSinceEpoch(start*1000).toUtc());
      print(date);
      

which is

I/flutter ( 5709): 16 Apr 03:00 PM 2021

Solution 11:[11]

convert utc number to DateTime:

  DateTime utcToDateTime(int utc) {
    return DateTime(1970, 1, 1).add(Duration(seconds: utc));
  }

  //test
  DateTime d = utcToDateTime(1649297709);
  print(d);