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

Jai*_*Jai 9 dart flutter

实际上在颤振中DateTime.now()是返回设备日期和时间。用户有时会改变他们的内部时钟,使用DateTime.now()可能会产生错误的结果。

  1. 如何在颤振中获取网络/服务器当前日期时间?
  2. 是否可以在不使用任何包的情况下获取网络/服务器当前日期时间

提前致谢!

Amo*_*ury 11

没有任何 api 调用是不可能的。

有一个插件可以让您从网络时间协议 (NTP) 获取精确时间。它在 dart 中实现了整个 NTP 协议。

这对于基于时间的事件很有用,因为 DateTime.now() 返回设备的时间。用户有时会更改他们的内部时钟并且使用 DateTime.now() 可能会给出错误的结果。您可以获取时钟偏移 [NTP.getNtpTime] 并在需要时手动将其应用于 DateTime.now() 对象(只需将偏移添加为毫秒持续时间),或者您可以从 [NTP.now] 获取已格式化的 [DateTime] 对象。

将此添加到您的包的 pubspec.yaml 文件中:

dependencies:
  ntp: ^1.0.7
Run Code Online (Sandbox Code Playgroud)

然后像这样添加代码:

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');
}
Run Code Online (Sandbox Code Playgroud)

  • ntp 包有网络替代品吗?由于 ntp 不支持 Flutter Web,我如何获取 Web 应用程序的网络时间? (3认同)

Bre*_*ung 5

尝试使用世界时钟 API。另外,要知道 api 有可能在某个时候失败......所以我建议在 http 调用周围使用 try-catch 块,如果它确实失败,只需返回设备的常规本地时间。 ...

  Future<void> getTime()async{
  var res = await http.get(Uri.parse('http://worldclockapi.com/api/json/est/now'));
  if (res.statusCode == 200){
  print(jsonDecode(res.body).toString());
}}
Run Code Online (Sandbox Code Playgroud)

  • 这个 URI 太慢了。`https://worldtimeapi.org/api/timezone/Etc/UTC` 更快 (2认同)