搜索插件、代码仓与 APP 分类

插件详情v2.0.0

ntp

从(NTP)网络时间协议服务器获取准确的时间或当前的 DateTime 对象。

AndroidiOSmacOSWindowsLinux
近 30 天下载
17.7万
喜欢数
261
Pub 分数
150

安装插件

flutter pub add ntp

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

ntp 包提供了一种从网络时间协议(NTP)服务器获取准确系统时间的简单方法。它使应用程序能够获得与全球时间标准同步的精确 DateTime 值,这在日志记录、调度或跨设备同步等对时间敏感的操作中尤其有用。该包支持 Android、iOS、macOS、Windows 和 Linux 等多个平台,确保在不同环境中的行为一致。它使用标准 NTP 协议,并提供易于使用的 API 来获取当前时间,而无需依赖本地设备时钟。

适合场景

  • 同步应用时间戳与全球时间
  • 提高基于时间的日志记录的准确性
  • 启用可靠的任务调度
  • 验证设备时钟漂移
  • 支持需要精确时间的分布式系统

主要特点

  • 从 NTP 服务器获取实时数据
  • 跨平台兼容性
  • 简单的同步和异步 API
  • 高精度时间获取
  • 最小依赖

适合对象

  • 需要高精度时间的应用程序
  • 时间敏感的服务
  • 物联网和后端系统
  • 需要同步时钟的移动和桌面应用程序
  • 时间验证的开发工具

使用建议

  • 需要互联网连接才能使用
  • 可能因网络状况而产生延迟
  • 不适用于离线使用
  • 服务器可用性影响可靠性
  • 时区处理必须单独管理

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

pub package CodeFactor

NTP

Plugin that allows you to get precise time from Network Time Protocol (NTP). It implements 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 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].

By default lookup address for NTP is: time.google.com

For example on how to use look in github library repository example/ folder.

How it works

Using int offset from getNtpTime()

  • default localTime is DateTime.now()
  • default lookUpAddress is 'time.google.com'
  • default port is 123
  DateTime startDate = new DateTime.now().toLocal();
  int offset = await NTP.getNtpOffset(localTime: startDate);
  print('NTP DateTime offset align: ${startDate.add(new Duration(milliseconds: offset))}');

Using DateTime from now

  DateTime startDate = await NTP.now();
  print('NTP DateTime: ${startDate}');
NTP Functions
  Future<int> getNtpOffset({
    String lookUpAddress: 'time.google.com',
    int port: 123,
    DateTime localTime,
    Duration timeout,
  });
  Future<DateTime> now();

所属分类

源码仓库

使用此插件的项目