Skip to content Skip to sidebar Skip to footer

How To Get Time From Network In Android

In my app I want to use the Network Time and not the time of device. It is the requirement of my app that time should be correct. I'm trying to get the time from NTS server but lo

Solution 1:

This solution is working for me:

Import in your module gradle this dependency (maybe you already have it):

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

Here you are a sample getting the local/net time. As you know, you should run it in an Async task as you did with your solution.

public static final String TIME_SERVER = "time-a.nist.gov";

public static void printTimes() throws IOException {
            NTPUDPClient timeClient = new NTPUDPClient();
            InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
            TimeInfo timeInfo = timeClient.getTime(inetAddress);
            //long returnTime = timeInfo.getReturnTime();   //local device time
            long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();   //server time

            Date time = new Date(returnTime);
            Log.e("getCurrentNetworkTime", "Time from " + TIME_SERVER + ": " + time);

            Log.e("Local time", "Local time");
            Log.e("Local time", "Current time: " + new Date(System.currentTimeMillis()));
            Log.e("Local time", "Time info: " + new Date(timeInfo.getReturnTime()));
            Log.e("Local time", "GetOriginateTimeStamp: " + new Date(timeInfo.getMessage().getOriginateTimeStamp().getTime()));

            Log.e("NTP time", "Time from " + TIME_SERVER + ": " + time);

            Log.e("Local time", "Time info: " + new Date(timeInfo.getMessage().getReceiveTimeStamp().getTime()));
            Log.e("Local time", "GetOriginateTimeStamp: " + new Date(timeInfo.getMessage().getTransmitTimeStamp().getTime()));

        }

Summary getting only your net time:

public static long getNetworkTime() throws IOException {
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        return timeInfo.getMessage().getReceiveTimeStamp().getTime();
    }

I hope this helps!!


Post a Comment for "How To Get Time From Network In Android"