我在Android应用程序开发方面有一些经验。现在我们开发了一个Android应用程序,我们需要谷歌或互联网的确切日期和时间。我已经从Stack Overflow和其他一些站点测试了一些代码,但它无法正常工作。该应用程序崩溃了。任何人都可以帮助我吗?
答案 0 :(得分:0)
试试这个:
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");
}
摇篮:
compile 'org.jsoup:jsoup:1.10.2'
答案 1 :(得分:0)
您可以使用以下程序从互联网时间服务器获取时间
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.您需要Apache Commons Net库来实现此目的。下载库并添加到项目构建路径中。
(或者您也可以在这里使用修剪过的Apache Commons Net Library:https://www.dropbox.com/s/bjxjv7phkb8xfhh/commons-net-3.1.jar。这足以从互联网上获取时间)
2.运行程序。您将在控制台上打印时间。
答案 2 :(得分:0)
这足以获得我想要的东西:
使用HttpGet,客户端和响应,我设法从响应日期标头中获取服务器的当前时间。我可以随时随地打电话给我,并会得到充满信心的回应(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());
}