如何在android中从互联网获取当前时间 [英] How to get current time from internet in android

查看:23
本文介绍了如何在android中从互联网获取当前时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个应用程序,我想在其中从 Internet 获取当前时间.

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

我知道如何使用 System.currentTimeMillis 从设备获取时间,即使搜索了很多,我也没有任何关于如何从互联网获取时间的线索.

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.

推荐答案

您可以使用以下程序从 Internet 时间服务器获取时间

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("time.nist.gov");
                System.out.println(client.getDate());
            } finally {
                client.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1.您需要 Apache Commons Net 库才能使其工作.下载库和添加到您的项目构建路径.

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

(或者您也可以在此处使用修剪后的 Apache Commons Net 库:https://www-us.apache.org/dist//commons/net/binaries/commons-net-3.6-bin.tar.gz这足以从互联网上获得时间)

(Or you can also use the trimmed Apache Commons Net Library here : https://www-us.apache.org/dist//commons/net/binaries/commons-net-3.6-bin.tar.gz This is enough to get time from internet )

2.运行程序.您将在控制台上打印时间.

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

这篇关于如何在android中从互联网获取当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆