Home > Software design >  Flutter - How to get my data variable's DateFormat and change timezone
Flutter - How to get my data variable's DateFormat and change timezone

Time:08-19

I am getting dates for a project through an API. The dates are in the format 2022-09-04T13:00:00 00:00 and I want to format this into two different variables - one that holds the date formatted as September 04, 2022 and one that holds the time formatted as 13:00. It has to be formatted with respect to the device's current timezone, but my issue is that I don't know which format the original date is in as I can't find what to write for the 00:00 part.

Since the date seems to be in UTC, I was thinking of a solution like below (based on other SO questions).

import 'package:intl/intl.dart';

// I need the correct format on the following line instead of  XX:XX
var dateValue = new DateFormat("yyyy-MM-ddTHH:mm:ss XX:XX").parseUTC("2022-09-04T13:00:00 00:00").toLocal();

String formattedDate = DateFormat("dd MMMM yyyy hh:mm").format(dateValue);
String formattedTime = DateFormat("HH:mm").format(dateValue);

Suggestions on better ways to do this are also appreciated.

CodePudding user response:

A single Z can represent the entire timezone in the formats, so the following solution works.

  import 'package:intl/intl.dart';

  var date = "2022-09-04T13:00:00 00:00";

  var dateValue = DateFormat('yyy-MM-ddTHH:mmZ').parseUTC(date).toLocal();

  String formattedDate = DateFormat("dd MMMM yyyy").format(dateValue);
  String formattedTime = DateFormat("HH:mm").format(dateValue);

CodePudding user response:

For date format, you can use DateFormat.yMMMMd('en_US') it will shows the date as September 04, 2022 . For time format, you can use DateFormat.Hm() so it will shows the time as 17:08 // force 24 hour time and DateFormat.jm() shows 5:08 PM.

Please read the documentaiton here

CodePudding user response:

You could parse it as a DateTime directly, at which Dart will per default recognize the 00:00 as timezone and interpret that as UTC.

To get the DateTime with respect to device current timezone, append the .toLocal() on the DateTime object, and format it as you please.

final incomingDate = '2022-09-04T13:00:00 00:00';
final dateValue = DateTime.parse(incomingDate); // dateValue.isUtc == true
final formatted1 = DateFormat('dd MMMM yyyy HH:mm').format(dateValue.toLocal());

Check this DartPad, and you can see examples.

  • Related