我正在制作一个应用程序,我想在其中从互联网获取当前时间。
我知道如何使用 System.currentTimeMillis
从设备上获取时间,即使经过大量搜索,我也没有得到任何关于如何从互联网上获取时间的线索。
最佳答案
您可以使用以下程序从互联网时间服务器获取时间
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("time.nist.gov");
System.out.println(client.getDate());
} finally {
client.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
1.您需要Apache Commons Net图书馆为此工作。 Download库并添加到您的项目构建路径。
(或者你也可以在这里使用修剪过的 Apache Commons Net Library:https://www-us.apache.org/dist//commons/net/binaries/commons-net-3.6-bin.tar.gz 这足以从互联网上获取时间)
2.运行程序。您将在控制台上打印时间。
关于android - 如何在android中从互联网获取当前时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13064750/