15

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.

  1. How can i get Network/Server Current DateTime in flutter ?
  2. Is it possible to get Network/Server Current DateTime Without using any packages ?

Thanks in advance!

Ken White
  • 120,522
  • 13
  • 212
  • 426
Jai Techie
  • 1,029
  • 8
  • 24
  • While I see that this question got quite a few upvotes, and so did the most popular answer (so apparently they are useful to some people), but I really don't think that there is such thing as "Network/Server Current DateTime". Why don't you trust your user (and their device) to have a "correctly" set up clock? Are you doing some kind of security solution? Which parties _are you_ willing to trust? – cubuspl42 Feb 03 '22 at 18:14
  • There's a decent chance that the only real solution to a problem you might have is implementing your checks on the _backend you control_. But that's of course just speculation. – cubuspl42 Feb 03 '22 at 18:18

3 Answers3

14

It's not possible without any API. You can use ntp plugin:

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');
}
iDecode
  • 12,616
  • 7
  • 58
  • 106
Amon Chowdhury
  • 1,348
  • 6
  • 15
  • 2
    Is there a web alternative for ntp package? Since ntp doesn't support Flutter web, how can I get network time for a web app? – rasitayaz Jun 11 '21 at 09:57
  • You can check the firebase network timestap. Or you can use any third-party API and call JSON request. – Amon Chowdhury Jun 14 '21 at 10:50
  • Note, that in this case the trust is put on Google, as that's the time server this package is using by default. Also note that NTP, as far as I know, does not support any kind of certificates. If you, let's say, want to protect your online multiplayer game from clock-based cheating with this solution, _it's a bad idea_. It's an okeyish idea _only_ if you don't trust the user to have the correct local time _but_ you are perfectly fine with the fact that nothing really stops the user from spoofing the timestamps on the NTP level. – cubuspl42 Feb 03 '22 at 18:26
  • I agree with you – Amon Chowdhury Feb 04 '22 at 10:28
0

Try using the world clock api. Also, know that there is a chance the api could fail at some point... So I would recommend using a try-catch block around the http call, and if it does happen to fail, just return regular local time of the device....

  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());
}}
Brett Young
  • 89
  • 2
  • 6
0

You must call a API for this, There are plenty of API's available

here is an example GET API for Indian time

http://worldtimeapi.org/api/timezone/Asia/Kolkata

The response will be like

  {
      "abbreviation": "IST",
      "client_ip": "45.125.117.46",
      "datetime": "2022-02-26T10:50:43.406519+05:30",
      "day_of_week": 6,
      "day_of_year": 57,
      "dst": false,
      "dst_from": null,
      "dst_offset": 0,
      "dst_until": null,
      "raw_offset": 19800,
      "timezone": "Asia/Kolkata",
      "unixtime": 1645852843,
      "utc_datetime": "2022-02-26T05:20:43.406519+00:00",
      "utc_offset": "+05:30",
      "week_number": 8
    }

If you dont know your country zone just call this API to get all timezones in the world

http://worldtimeapi.org/api/timezone/

Anandh Krishnan
  • 804
  • 7
  • 16