user1726619 user1726619 - 7 days ago 4
Android Question

How to get current time from internet in android

I am making an app in which I want to get the current time from internet.

I know how to get the time from the device using

System.currentTimeMillis
, and even after searching a lot, I did not get any clue about how to get it from internet.

Answer

You can get time from internet time servers using the below program

import java.io.IOException;

import org.apache.commons.net.time.TimeTCPClient;

public final class GetTime {

    public static final void main(String[] args) {
        try {
            TimeTCPClient client = new TimeTCPClient();
            try {
                // Set timeout of 60 seconds
                client.setDefaultTimeout(60000);
                // Connecting to time server
                // Other time servers can be found at : http://tf.nist.gov/tf-cgi/servers.cgi#
                // Make sure that your program NEVER queries a server more frequently than once every 4 seconds
                client.connect("nist.time.nosc.us");
                System.out.println(client.getDate());
            } finally {
                client.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1.You would need Apache Commons Net library for this to work. Download the library and add to your project build path.

(Or you can also use the trimmed Apache Commons Net Library here : https://www.dropbox.com/s/bjxjv7phkb8xfhh/commons-net-3.1.jar. This is enough to get time from internet )

2.Run the program. You will get the time printed on your console.

Comments