android - 如何在android中从互联网获取当前时间

标签 android time

我正在制作一个应用程序,我想在其中从互联网获取当前时间。

我知道如何使用 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/

相关文章:

c++ - 在 C++ 中测量 CPU 时间

java - 使用日历更新时间

Javascript new Date().getTime 早于 newDate(year,month...)

android - Unity android中的水平面检测

java - SQLite ID 列和 onItemLongClick

Jetpack Compose 中的 android:autoSizeTextType

在欧洲使用 RTL-SDR USB Dongle 接收时间信号?

java - Android BroadcastReceiver 注册时出现空指针异常

java - 我想从一个 Activity 调用两个 ContentView

python - 如何将 datetime.date 对象转换为 time.struct_time 对象?