【问题标题】:get current Date from internet in android在android中从互联网获取当前日期
【发布时间】:2015-07-31 03:51:21
【问题描述】:

我想知道 android 中是否有任何 API/类可以为我们提供原始日期,因为我不想从 android 设备获取日期/时间。

【问题讨论】:

标签: android date datetime android-asynctask


【解决方案1】:

更新!!

旧答案不起作用,因为 timeapi.org 已关闭。

这是我的新 getTime 方法。它正在使用 JSOUP

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());
}

将时间戳转换为可读的日期和时间

private String getDate(long time) {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time * 1000);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm a", Locale.ENGLISH);
    
    return dateFormat.format(cal.getTime());
} 

分级:

implementation 'org.jsoup:jsoup:1.10.2'

【讨论】:

    【解决方案2】:

    使用这个

    public String getTime() {
    try{
        //Make the Http connection so we can retrieve the time
        HttpClient httpclient = new DefaultHttpClient();
        // I am using yahoos api to get the time
        HttpResponse response = httpclient.execute(new
        HttpGet("http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo"));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            // The response is an xml file and i have stored it in a string
            String responseString = out.toString();
            Log.d("Response", responseString);
            //We have to parse the xml file using any parser, but since i have to 
            //take just one value i have deviced a shortcut to retrieve it
            int x = responseString.indexOf("<Timestamp>");
            int y = responseString.indexOf("</Timestamp>");
            //I am using the x + "<Timestamp>" because x alone gives only the start value
            Log.d("Response", responseString.substring(x + "<Timestamp>".length(),y) );
            String timestamp =  responseString.substring(x + "<Timestamp>".length(),y);
            // The time returned is in UNIX format so i need to multiply it by 1000 to use it
            Date d = new Date(Long.parseLong(timestamp) * 1000);
            Log.d("Response", d.toString() );
            return d.toString() ;
        } 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());
    }
    return null;
    }
    

    【讨论】:

    【解决方案3】:

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

        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。这足以从互联网上获得时间)

    【讨论】:

      【解决方案4】:

      您可以使用android.net.sntp.SntpClient 类。

      SntpClient client = new SntpClient();
      int timeout = 50000;
      if (client.requestTime("time-a.nist.gov", timeout)) {
          long time = client.getNtpTime();
          Calendar calendar = Calendar.getInstance();
          calendar.setTimeInMillis(time);
          calendar.getTime();  // this should be your date
      }
      

      【讨论】:

        猜你喜欢
        • 2012-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-08
        • 1970-01-01
        • 1970-01-01
        • 2012-01-29
        • 1970-01-01
        相关资源
        最近更新 更多