Actually in flutter DateTime.now()
is returns device date and time. Users sometimes change their internal clock and using DateTime.now()
can give w
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');
}