从 Android 中的 Google 获取当前日期和时间

Get current date and time from Google in Android

我在 Android 应用程序开发方面有一些经验。现在我们开发了一个 Android 应用程序,我们需要来自 Google 或互联网的确切日期和时间。我已经测试了一些来自 Stack Overflow 和其他一些网站的代码,但它没有正常工作。该应用程序崩溃了。谁能帮帮我?

试试这个:

private long getTime() throws Exception {
    String url = "https://time.is/Unix_time_now";
    Document doc = Jsoup.parse(new URL(url).openStream(), "UTF-8", url);
    String[] tags = new String[] {
            "div[id=time_section]",
            "div[id=clock0_bg]"
    };
    Elements elements= doc.select(tags[0]);
    for (int i = 0; i <tags.length; i++) {
        elements = elements.select(tags[i]);
    }
    return Long.parseLong(elements.text() + "000");
}

Gradle:

compile 'org.jsoup:jsoup:1.10.2'

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

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 需要 Apache Commons Net 库才能工作。下载库并添加到您的项目构建路径。

(或者您也可以在此处使用经过修剪的 Apache Commons Net 库:https://www.dropbox.com/s/bjxjv7phkb8xfhh/commons-net-3.1.jar。这足以从互联网获取时间)

2.Run 程序。您将在控制台上打印时间。

这足以得到你想要的:

使用 HttpGet、客户端和响应,我设法从响应日期 Header 获取服务器的当前时间。我可以随时调用它,并且会得到自信的响应(Google 几乎 100% 可用,我可以相信获得正确的日期和时间)

try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            String dateStr = response.getFirstHeader("Date").getValue();
            //Here I do something with the Date String
            System.out.println(dateStr);

        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    }catch (ClientProtocolException e) {
        Log.d("Response", e.getMessage());
    }catch (IOException e) {
        Log.d("Response", e.getMessage());
    }