Reputation: 21
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
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
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.
Upvotes: 1
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
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