'Get actual time from internet ?

How to get 'current(actual) time' or 'network operator's time' programmatically if device time is changed ?

I'm trying to get current time through 'getLastKnownLocation' method of 'LocationManager' class. But it gives last location time, but I need current time.

Can anyone tell me a clue about the correct way to get actual time from internet ?

  • If possible without using any external library.

Thanks in advance.



Solution 1:[1]

You can use a rest full api provided by geo names http://www.geonames.org/login it will require lat and long for this purpose for example

http://api.geonames.org/timezoneJSON?lat=51.5034070&lng=-0.1275920&username=your_user_name

Solution 2:[2]

According to this answer you can get the current time from an NTP server.

support.ntp.org library

Add to your dependency

String timeServer = "server 0.pool.ntp.org";
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(timeServer);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getReturnTime();
System.out.println(returnTime)

Solution 3:[3]

Getting the time from the third-party servers is not reliable most of the times and some of them are paid services.

If you want to get the exact time and check with the phone whether it is correct or not, irrespective of the proper way, you can use the following simple trick to get the actual time.

private class GetActualTime extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            try {
                HttpURLConnection urlConnection = null;
                StringBuilder result = new StringBuilder();
                try {
                    URL url = new URL(urls[0]);
                    urlConnection = (HttpURLConnection) url.openConnection();
                    int code = urlConnection.getResponseCode();
                    if (code == 200) {
                        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                        String line = "";
                        while ((line = bufferedReader.readLine()) != null)
                        result.append(line);
                        in.close();
                    }
                        else {
                        return "error on fetching";
                    }
                    return result.toString();
                } catch (MalformedURLException e) {
                    return "malformed URL";
                } catch (IOException e) {
                   return "io exception";
                } finally {
                    if (urlConnection != null) {urlConnection.disconnect();
                    }
                }
            } catch (Exception e) { return "null"; }
        }

        @Override
        protected void onPostExecute(String time) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat mdformat = new SimpleDateFormat("h:mm");
            String times =  mdformat.format(calendar.getTime());
            try {
                String areatime = time.substring(time.indexOf(String.valueOf(times)), time.indexOf(String.valueOf(times)) + 5).trim(); 
                        Toast.makeText(this, "The actual time is " + areatime, Toast.LENGTH_SHORT).show();

            }
            catch(IndexOutOfBoundsException e){
                        Toast.makeText(this, "Mobile time is not same as Internet time", Toast.LENGTH_SHORT).show();
                }
            }


        }

    }

Call the class in the onCreate();

new GetActualTime().execute("https://www.google.com/search?q=time");

So this is actually getting the time from Google. This works pretty awesomely in my projects. In order to check whether the system time is wrong, you can use this trick. Instead of depending on the time servers, you can trust Google.

As it is more sensitive in checking, even a minute ahead or lag will catch the exception. You can customise the code if you want to handle that.

Solution 4:[4]

For Android:

Add to gradle app module:

compile 'commons-net:commons-net:3.3'

Add to your code:

...
String TAG = "YOUR_APP_TAG";
String TIME_SERVER = "0.europe.pool.ntp.org";
...
public void checkTimeServer() {
    try {
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        long setverTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();

        // store this somewhere and use to correct system time
        long timeCorrection = System.currentTimeMillis()-setverTime;    
    } catch (Exception e) {
        Log.v(TAG,"Time server error - "+e.getLocalizedMessage());
    }
}

NOTE: timeInfo.getReturnTime() as mentioned in an earlier answer will get you local system time, if you need server time you must use timeInfo.getMessage().getTransmitTimeStamp().getTime().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nasch
Solution 2
Solution 3 Pradeep
Solution 4 Nenad Miodrag