Flutter如何获取网络DateTime.Now()? [英] Flutter How to get network DateTime.Now()?
问题描述
实际上是波动的 DateTime.now()
返回设备日期和时间.用户有时会更改其内部时钟,并且使用 DateTime.now()
可能会得出错误的结果.
Actually in flutter DateTime.now()
is returns device date and time. Users sometimes change their internal clock and using DateTime.now()
can give wrong result.
- 如何快速获取网络/服务器当前日期时间?
- 是否可以在不使用任何软件包的情况下获取网络/服务器当前日期时间?
提前谢谢!
推荐答案
没有任何api调用是不可能的.
有一个插件,可让您从网络时间协议(NTP)中获取准确的时间.它在dart中实现了整个NTP协议.
There is a plugin that allows you to get precise time from Network Time Protocol (NTP). It implements the whole NTP protocol in dart.
这对于基于时间的事件很有用,因为DateTime.now()返回设备的时间.用户有时会更改其内部时钟,并且使用DateTime.now()可能会给出错误的结果.您可以只获取时钟偏移量[NTP.getNtpTime]并在需要时将其手动应用于DateTime.now()对象(只需将偏移量添加为毫秒的持续时间),也可以从[NTP.now]获取已格式化的[DateTime]对象.
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文件中:
Add this to your package's pubspec.yaml file:
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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!