UniquelyAnonymous
UniquelyAnonymous

Reputation: 21

Finding exact Date Time in Android Studio

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?

Upvotes: 2

Views: 636

Answers (4)

Andreas
Andreas

Reputation: 159135

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.

Upvotes: 0

Michalis Vitos
Michalis Vitos

Reputation: 23

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.

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

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.

Upvotes: 0

JakeD
JakeD

Reputation: 457

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.

Upvotes: 0

Related Questions