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.
Thanks in advance!
now() function to get the current date in Flutter. You do not need to import anything to use the DateTime module. This is an in-built module of Dart and you can use its now() function to get the current date with time. DateTime datetime = DateTime.
In this blog post, let’s learn how to get current date in flutter. There’s a DateTime class in Dart which can be used to get current date and time. This will give us the output as following. Most of the time we want to show the current date in string. You can convert DateTime to string using Intl package.
There’s a DateTime class in Dart which can be used to get current date and time. This will give us the output as following. Most of the time we want to show the current date in string.
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].
First of All Import material.dart, async, and intl Package in your main.dart file. import 'dart:async'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; Then, Create void main and Define MyApp in your runApp. Now, Create a class named MyApp extends with a Stateless widget. This is our main View class. and define
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<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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With