How to convert DateTime into different timezones?

前端 未结 4 1465
囚心锁ツ
囚心锁ツ 2021-01-02 04:02

How to convert DateTime into different timezones? The DateTime class has two methods .toLocal() and .toUtc(). But if I want to display time in another time zone. How can I d

相关标签:
4条回答
  • 2021-01-02 04:22

    You can use TimeZoneInfo.ConvertTime() to change timezone. Try like this

    DateTime hwTime = new DateTime(2007, 02, 01, 08, 00, 00);
    try {
        TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");
        TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local));
    }
    catch (TimeZoneNotFoundException) {
        Console.WriteLine("Timezone not found");
    }                           
    catch (InvalidTimeZoneException) {
        Console.WriteLine("Invalid Timezone");
    }
    

    This will convert from Hawaiian Standard Time to Local.

    It is just an example. Use it to convert as per your need.

    0 讨论(0)
  • 2021-01-02 04:24

    DateTime doesn't contain timezone information therefore you can't create a DateTime in a specific timezone only the timezone of your system and UTC are available.

    You can wrap the DateTime in a custom class and add timezone information to the wrapper. You also need a table of offsets for each timezone and then add/substract the offset from the UTC date.

    0 讨论(0)
  • 2021-01-02 04:29

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

    The basic usage for converting a DateTime to a timezone is very simple:

    //Assumes Instant is in your pubspec
    import 'package:instant/instant.dart';
    
    //Super Simple!
    DateTime myDT = DateTime.now(); //Current DateTime
    DateTime EastCoast = dateTimeToZone(zone: "EST", datetime: myDT); //DateTime in EST zone
    return EastCoast;
    

    This works with one line of code and minimal hassle.

    0 讨论(0)
  • 2021-01-02 04:39
    import 'package:timezone/timezone.dart'
    
    String locationLocal = await FlutterNativeTimezone.getLocalTimezone();
    
    //Esta Função recebe uma data/hora e converte para data/hora local.
    TZDateTime convertFireBaseToLocal(TZDateTime tzDateTime, String locationLocal) {
          TZDateTime nowLocal = new TZDateTime.now(getLocation(locationLocal));
          int difference = nowLocal.timeZoneOffset.inHours;
          TZDateTime newTzDateTime;
          newTzDateTime = tzDateTime.add(Duration(hours: difference));
          return newTzDateTime;
    }
    
    0 讨论(0)
提交回复
热议问题