Get actual time from internet ?

2019-05-10 14:37发布

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.

4条回答
仙女界的扛把子
2楼-- · 2019-05-10 15:06

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

查看更多
贼婆χ
3楼-- · 2019-05-10 15:12

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)
查看更多
Juvenile、少年°
4楼-- · 2019-05-10 15:22

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

查看更多
相关推荐>>
5楼-- · 2019-05-10 15:29

Try this :

System.currentTimeMillis();
查看更多
登录 后发表回答