5

I am a newbie to Dart. I am currently facing a problem to format my DateTime to display the time based on the device's timezone. Can someone advise me how can I achieve that? My current code as following:

DateFormat('dd MMM yyyy hh:mm')

Output Sample: 11 Mar 2019 07:04

Expectation: My device is using GMT+8 at the moment, I am expecting it to display as 11 Mar 2019 15.04.

Please advise. Thanks!!

user3180690
  • 173
  • 1
  • 3
  • 6

4 Answers4

23

For converting UTC to Local Timezone :

import 'package:intl/intl.dart';

var dateValue = new DateFormat("yyyy-MM-ddTHH:mm:ssZ").parseUTC("2020-06-14T18:55:21Z").toLocal();
String formattedDate = DateFormat("dd MMM yyyy hh:mm").format(dateValue);
debugPrint("formattedDate = "+formattedDate);
Rafi
  • 833
  • 13
  • 17
  • 3
    Oh, finally. Thank you, I've been struggling converting a simple UTC date in local timezone for about 2 hours, it's ridiculous, lol. – briosheje Sep 26 '20 at 15:53
4

To make sure your DateTime uses the device's current timezone always use toLocal().

DateTime.toLocal() documentation: https://api.dart.dev/stable/2.18.5/dart-core/DateTime/toLocal.html

So simply do:

DateFormat('dd MMM yyyy hh:mm').format(myDate.toLocal())
Shahar Hajdu
  • 315
  • 2
  • 4
3

I fetched data from laravel api

laravel dateTimeUTC like 2021-05-21T17:33:24.000000Z

import 'package:intl/intl.dart';


String dateTime = "2021-05-21T17:33:24.000000Z" // String datetime UTC zone

DateTime parsedDateFormat = DateFormat("yyyy-MM-ddTHH:mm:ssZ").parseUTC(dateTime).toLocal(); // parse String datetime to DateTime and get local date time 

String formatedDateTime = DateFormat.yMd().add_jm().format(parsedDateFormat).toString(); // convert local date time to string format local date time

// output is 5/21/2021 11:03PM
Micro Jafar
  • 61
  • 1
  • 2
-2

Install the intl package and then use the DateFormat.

import 'package:intl/intl.dart';
final dateFormatter = DateFormat('d MMMM yyyy hh:mm');
print(dateFormatter.format(your_date_time_object));
Kalpesh
  • 4,020
  • 4
  • 18
  • 27
Filled Stacks
  • 4,116
  • 1
  • 23
  • 36