如何在android中从internet获取当前时间

如何在android中从internet获取当前时间,android,time,Android,Time,我正在制作一个应用程序,我想从互联网上获取当前时间 我知道如何使用系统从设备获取时间。currentTimeMillis,即使搜索了很多,我也没有得到任何关于如何从internet获取时间的线索。您需要访问以XML或JSON格式提供当前时间的Web服务 如果找不到这种类型的服务,可以解析网页上的时间,例如,或者使用简单的PHP页面在服务器上托管自己的时间服务 查看JSoup以解析HTML页面。您可以使用以下程序从internet时间服务器获取时间 import java.io.IOExcepti

我正在制作一个应用程序,我想从互联网上获取当前时间


我知道如何使用
系统从设备获取时间。currentTimeMillis
,即使搜索了很多,我也没有得到任何关于如何从internet获取时间的线索。

您需要访问以XML或JSON格式提供当前时间的Web服务

如果找不到这种类型的服务,可以解析网页上的时间,例如,或者使用简单的PHP页面在服务器上托管自己的时间服务


查看JSoup以解析HTML页面。

您可以使用以下程序从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("time.nist.gov");
                System.out.println(client.getDate());
            } finally {
                client.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
1.你需要一个图书馆才能让它工作。库并添加到项目生成路径中

(或者您也可以在这里使用修剪过的Apache Commons Net库:这足以从internet获得时间)


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;
}
公共字符串getTime(){
试一试{
//建立Http连接以便我们可以检索时间
HttpClient HttpClient=新的DefaultHttpClient();
//我正在使用YahoosAPI获取时间
HttpResponse response=httpclient.execute(新建
HttpGet(“http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo"));
StatusLine StatusLine=response.getStatusLine();
if(statusLine.getStatusCode()==HttpStatus.SC\u OK){
ByteArrayOutputStream out=新建ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
//响应是一个xml文件,我已将其存储在字符串中
字符串responseString=out.toString();
日志d(“响应”,响应预算);
//我们必须使用任何解析器解析xml文件,但由于我必须
//只取一个值,我设置了一个快捷方式来检索它
int x=responseString.indexOf(“”);
int y=responseString.indexOf(“”);
//我使用x+“”是因为x本身只给出起始值
Log.d(“Response”,responseString.substring(x+“”.length(),y));
字符串时间戳=responseString.substring(x+“”.length(),y);
//返回的时间是UNIX格式的,所以我需要将它乘以1000才能使用它
日期d=新日期(长.parseLong(时间戳)*1000);
Log.d(“Response”,d.toString());
返回d.toString();
}否则{
//关闭连接。
response.getEntity().getContent().close();
抛出新IOException(statusLine.getReasonPhrase());
}
}捕获(客户端协议例外e){
Log.d(“Response”,e.getMessage());
}捕获(IOE异常){
Log.d(“Response”,e.getMessage());
}
返回null;
}

我认为最好的解决方案是使用SNTP,特别是Android本身的SNTP客户端代码,例如:

我相信当手机网络不可用时(例如wifi平板电脑),Android会使用SNTP自动更新日期/时间

我认为它比其他解决方案更好,因为它使用SNTP/NTP,而不是ApacheTimeTCPClient使用的时间协议(RFC 868)。我不知道RFC 868有什么不好的地方,但NTP是更新的,似乎已经取代了它,并且得到了更广泛的应用。我相信没有手机的Android设备使用NTP


另外,因为它使用套接字。建议的一些解决方案使用HTTP,因此在准确性方面会有所损失。

以上内容对我来说都不管用。这就是我最后的结果(截击)
此示例还将转换为另一个时区

    Long time = null;
    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="http://www.timeapi.org/utc/now";

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                        Date date = simpleDateFormat.parse(response);

                        TimeZone tz = TimeZone.getTimeZone("Israel");
                        SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        destFormat.setTimeZone(tz);

                        String result = destFormat.format(date);

                        Log.d(TAG, "onResponse: " + result.toString());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.w(TAG, "onErrorResponse: "+ error.getMessage());
        }
    });
    queue.add(stringRequest);
    return time;

如果您不关心毫秒精度,如果您已经在使用google firebase或不介意使用它(他们提供免费层),请查看以下内容:

基本上,firebase数据库有一个字段,提供设备时间和firebase服务器时间之间的偏移值。可以使用此偏移量获取当前时间

DatabaseReference offsetRef = FirebaseDatabase.getInstance().getReference(".info/serverTimeOffset");
offsetRef.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    double offset = snapshot.getValue(Double.class);
    double estimatedServerTimeMs = System.currentTimeMillis() + offset;
  }

  @Override
  public void onCancelled(DatabaseError error) {
    System.err.println("Listener was cancelled");
  }
});

正如我所说,基于网络延迟,这将是不准确的。

我使用了截击。。并从服务器api(php)获得时间

public void GetServerTime(){
StringRequest-volleyrequest=新建StringRequest(Request.Method.GET,url,new
Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
试一试{
JSONObject jObject=新JSONObject(响应);
结果=jObject.toString();
}catch(JSONException | ParseException e){
e、 printStackTrace();
Toast.makeText(getApplicationContext(),“数据转换失败”,Toast.LENGTH_LONG.show();
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
错误。printStackTrace();
Log.w(“onErrorResponse”,“error.getMessage());
Toast.makeText(getApplicationContext(),“没有Internet连接!请检查您的网络。”,Toast.LENGTH_LONG).show();
}
});
RequestQueue=Volley.newRequestQueue(ProductDetailActivity.this);
添加(截击请求);
}
在得到时间之后。我不能为我的目的使用。。 (我的目的)
我有每个产品的结束时间,我必须将我的当前时间与产品结束时间进行比较。。如果有效,可以将其添加到购物车的其他版本号中。

检查可能会帮助您对不起,先生,我是android新手,这个例子很难理解。请告诉我先生如何解析这个网站上的时间。这对我这样的初学者非常有帮助。提前谢谢。它的服务非常昂贵。先生。你能给我一些免费api服务提供商的链接吗?请看一下JSoup文档,尝试一些代码,请注意,尽管您可以使用Jsoup解析TimeAndDate,但该网页的来源显示“下载内容传输的脚本和程序”
DatabaseReference offsetRef = FirebaseDatabase.getInstance().getReference(".info/serverTimeOffset");
offsetRef.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    double offset = snapshot.getValue(Double.class);
    double estimatedServerTimeMs = System.currentTimeMillis() + offset;
  }

  @Override
  public void onCancelled(DatabaseError error) {
    System.err.println("Listener was cancelled");
  }
});
         public void GetServerTime() {

        StringRequest volleyrequest = new StringRequest(Request.Method.GET, url, new 
         Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {

                JSONObject jObject = new JSONObject(response);
                result = jObject.toString();

            } catch (JSONException | ParseException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Data Conversion Failed.", Toast.LENGTH_LONG).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            Log.w("onErrorResponse", "" + error.getMessage());
            Toast.makeText(getApplicationContext(), "NO Internet connection! Please check your network.", Toast.LENGTH_LONG).show();
        }
    });

    RequestQueue queue = Volley.newRequestQueue(ProductDetailActivity.this);
    queue.add(volleyrequest);
}