2

I am creating an android app and I need to get the EXACT date and time using android studio. There are many questions which have solutions to this, but I realised that all of them give the phone's time which can be edited by the user. I need the exact world-standard time.

Currently, the code I'm using is this:

DateFormat dfgmt = new java.text.SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
            dfgmt.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
            String nowTime = dfgmt.format(new Date());

But this is giving me the time which is at times tweaked by the user. Anyone has a way to get the exact time?

  • There is probably an API u can call to get the time...or maybe hit google. – brso05 May 29 '18 at 15:14
  • Possible duplicate of [How to get current time from internet in android](https://stackoverflow.com/questions/13064750/how-to-get-current-time-from-internet-in-android) – Amir Dora. May 29 '18 at 15:54

4 Answers4

1

There are few different approaches that you could follow, based on whether you have access to the internet and/or GPS, and whether you want this functionality to work offline.

  1. As others have suggested, you could use an online service to get the official time. For example, TimezoneDB provides such a REST API.
  2. If you need to access the time offline, read the time from the GPS provider, which returns the time in UTC format. Check Location.getTime().
  3. Use a combination of an online service to get the time once and combine it with SystemClock.elapsedRealtime() to get the actual real time after that, even if the device is offline.
0

You could use an external service for this. You could set up a simple REST API or use someone else's (check this post which gives an example of one Free Rest API to get current time as string (timezone irrelevant)) to make HTTP requests and get the time irrelevant of what is set on the user's phone.

JakeD
  • 407
  • 2
  • 7
  • 19
0

You can ask the time to a remote server.

This will grant you that the time is not setted manually by the user and is not influenced by the timezone.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

Use a 3rd-party NTP client library to get current time from an NTP server.

E.g. Apache Commons Net has a class for that.

Andreas
  • 154,647
  • 11
  • 152
  • 247