Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a DateTime instance in a specific timezone?

Tags:

dart

I am calling a legacy service that returns all times in a string format assuming that the timezone is EST. How do I create a DateTime instance and specify that the timezone is EST? When I display the times to the user's I will translate to their device timezone.

like image 763
dakamojo Avatar asked Oct 20 '25 14:10

dakamojo


1 Answers

I wrote a package for this. It's called Instant, and it can fetch the latest DateTime in any given zone worldwide. Take a detailed look at https://aditya-kishore.gitbook.io/instant/

The basic usage to get a DateTime in a timezone is fairly simple.

Note: I assume below that your legacy service delivers a String with format HH:MM in 24 hr time, and that it doesn't deliver a date. If any of the following is untrue, lemme know and I'll change the code sample.

List<int> _hourmin (String parse) {
  List<int> timeinint = [];
  if (parse.length == 5) {
    //if parse is something like 10:00
    timeinint.add(int.parse(parse.substring(0,2))); //Add hours (10)
    timeinint.add(int.parse(parse.substring(3,5))); //Add minutes (0)
  } //hours >= 10
  if (parse.length == 4) {
    //if parse is something like 4:06
    timeinint.add(int.parse(parse.substring(0,1))); //Add hours (4)
    timeinint.add(int.parse(parse.substring(2,4))); //Add minutes (6)
  } //hours < 10
  return timeinint;
}

DateTime utcDateTimeFromZone(
    {@required String zone,
    int year = 0,
    int month = 0,
    int day = 0,
    int hour = 0,
    int minute = 0,
    int second = 0,
    int millisecond = 0,
    int microsecond = 0}) {

  hour = (hour - timeZoneOffsets[zone].truncate()) % 24; //Convert to UTC from timezone
  if (hour<0) {
    hour = 24 + hour;
  }
  minute = (minute - ((timeZoneOffsets[zone]%1)*60).round()) % 60;
  if (minute<0) {
    minute = 60 + minute;
  }
//Convert to UTC from timezone
  DateTime inUTC = DateTime.utc(year, month, day, hour, minute, second, millisecond, microsecond); //Initialize in UTC time
  return inUTC;
}

  //We get an array containing the hours minutes
  List<int> time = _hourmin("4:25"); //put your API call as the param here
  //This is what you need
  DateTime finished = utcDateTimeFromZone(zone: "EST", hour: time[0], minute: time[1]);

  print(formatTime(time: finished.toLocal())); //1:25 for me, because I'm PST, but this works with any local timezone

Hope that clears it up!

like image 169
AKushWarrior Avatar answered Oct 22 '25 04:10

AKushWarrior