Flutter How to get network DateTime.Now()?

前端 未结 1 1484
长发绾君心
长发绾君心 2021-01-19 02:38

Actually in flutter DateTime.now() is returns device date and time. Users sometimes change their internal clock and using DateTime.now() can give w

1条回答
  •  礼貌的吻别
    2021-01-19 03:09

    It's not possible without any api call.

    There is a plugin that allows you to get precise time from Network Time Protocol (NTP). It implements the whole NTP protocol in dart.

    This is useful for time-based events since DateTime.now() returns the time of the device. Users sometimes change their internal clock and using DateTime.now() can give the wrong result. You can just get clock offset [NTP.getNtpTime] and apply it manually to DateTime.now() object when needed (just add offset as milliseconds duration), or you can get already formatted [DateTime] object from [NTP.now].

    Add this to your package's pubspec.yaml file:

    dependencies:
      ntp: ^1.0.7
    

    Then add the code like this:

    import 'package:ntp/ntp.dart';
    
    Future main() async {
      DateTime _myTime;
      DateTime _ntpTime;
    
      /// Or you could get NTP current (It will call DateTime.now() and add NTP offset to it)
      _myTime = await NTP.now();
    
      /// Or get NTP offset (in milliseconds) and add it yourself
      final int offset = await NTP.getNtpOffset(localTime: DateTime.now());
      _ntpTime = _myTime.add(Duration(milliseconds: offset));
    
      print('My time: $_myTime');
      print('NTP time: $_ntpTime');
      print('Difference: ${_myTime.difference(_ntpTime).inMilliseconds}ms');
    }
    

    0 讨论(0)
提交回复
热议问题