2

I have a date in this format: "Mon May 31 2021 23:59:59 GMT+0000 (Coordinated Universal Time)" but need to to convert it into a local time zone and parse it as a DateTime format. How do I do this?

R_Dax
  • 706
  • 3
  • 10
  • 25
  • Hello, welcome to SO. What have you tried so far? What result (or error) do you get and how does that differ from your desired output? It might help if you edited the question to include these details with some code you have written. – R_Dax May 21 '21 at 15:13
  • It had been suggested that this question be a duplicate of [How do I convert a date/time string to a DateTime object in Dart?](https://stackoverflow.com/questions/49385303/how-do-i-convert-a-date-time-string-to-a-datetime-object-in-dart). I don’t think it’s an *exact* duplicate. Check for yourself, please, and let us know if that question answers yours. – Ole V.V. May 22 '21 at 05:51

2 Answers2

0

When working with date and time in Flutter you can use the DateTime class.

To convert utc time to local you can do:

var myUTCTime = DateTime.utc(2021, DateTime.may, 31);
var localTime = myUTCTime.toLocal();

Here is the format to declare a time:

DateTime.utc(int year, [int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0])

Feel free to run the above code in dartpad with a print statement to see the output!

Benjamin Carlson
  • 295
  • 3
  • 13
0

Cannot directly parse this string with DateTime object. Instead, use this function -

DateTime getLocalTimeStamp(String timeData) {
  Map<String, int> months = {"January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12};
  List<String> splittedTime = timeData.split(" ").toList();
  String monthString = months[splittedTime[1]].toString().length < 10
     ? "0"+months[splittedTime[1]].toString()
     : months[splittedTime[1]].toString();
  String cleanedDate = splittedTime[3]+"-"+monthString+"-"+splittedTime[2]+"T"+splittedTime[4];
  DateTime parsedDate = DateTime.parse(cleanedDate);
  return parsedDate;
}

Somethings Like This -

void main() {
  DateTime res = getLocalTimeStamp("Mon May 31 2021 23:59:59 GMT+0000");
  print(res.day);
}
robben
  • 637
  • 1
  • 7
  • 14