Tejas Patel
Tejas Patel

Reputation: 250

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 ?

Thanks in advance.

Upvotes: 5

Views: 8019

Answers (5)

Pradeep
Pradeep

Reputation: 808

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.

Upvotes: 2

Nenad Miodrag
Nenad Miodrag

Reputation: 39

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().

Upvotes: 3

Sathish Kumar
Sathish Kumar

Reputation: 957

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)

Upvotes: 4

Adeel Turk
Adeel Turk

Reputation: 907

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

Upvotes: 3

yozzy
yozzy

Reputation: 344

Try this :

System.currentTimeMillis();

Upvotes: -3

Related Questions