get current Date from internet in android

六月ゝ 毕业季﹏ 提交于 2020-05-28 07:36:05

问题


I want to know if there is any API/class in android which can give us the original date as I do not want to get the date/time from android device.


回答1:


Updated!!

The old answer does not work because the timeapi.org is down.

Here is the my new getTime method. It's using 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() + "000");
}

Gradle:

compile 'org.jsoup:jsoup:1.10.2'



回答2:


You can get UTC time from http://www.timeapi.org/utc/now and convert it to your local time format.




回答3:


Use This

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



回答4:


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

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

(Or you can also use the trimmed Apache Commons Net Library here : https://www.dropbox.com/s/bjxjv7phkb8xfhh/commons-net-3.1.jar. This is enough to get time from internet )




回答5:


You can use the android.net.sntp.SntpClient class.

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
}


来源:https://stackoverflow.com/questions/30323583/get-current-date-from-internet-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!