gpt4 book ai didi

flutter - 如何获取网络 DateTime.Now()?

转载 作者:行者123 更新时间:2023-12-03 02:52:06 27 4
gpt4 key购买 nike

其实在 flutter DateTime.now()是返回设备日期和时间。用户有时会更改其内部时钟并使用 DateTime.now()可以给出错误的结果。

  • 我怎样才能得到 网络/服务器当前日期时间 在 flutter 中?
  • 有没有可能得到网络/服务器当前日期时间 不使用任何软件包?

  • 提前致谢!

    最佳答案

    没有任何 API 是不可能的 .您可以使用 ntp 插入:

    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].


    将此添加到包的 pubspec.yaml 文件中:
    dependencies:
    ntp: ^1.0.7
    然后像这样添加代码:
    import 'package:ntp/ntp.dart';

    Future<void> 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');
    }

    关于flutter - 如何获取网络 DateTime.Now()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64026825/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com