从Google NTP服务器获取当前日期和时间

时间:2018-02-05 17:02:02

标签: java android

我想从谷歌ntp服务器获取当前GMT时间。任何人都可以使用AsyncTask修改代码? NTP服务器是否提供空值? 我知道下面的代码中存在一些问题。 我是新开发者帮我解决这个问题。

我找到了答案:

SntpClient client = new SntpClient();
if (client.requestTime("time.google.com")) {
    long now = client.getNtpTime() + SystemClock.elapsedRealtime() - 
    client.getNtpTimeReference();
    Date current = new Date(now);
    Log.i("NTP tag", current.toString());
}

2 个答案:

答案 0 :(得分:1)

即时通过谷歌获取此代码的时间,你应该尝试一下,也许它会有所帮助 我的代码所做的是,它转到google.com页面并检索时间,然后我以"EEE, d MMM yyyy HH:mm:ss z"格式获得时间,然后将其转换为秒以上传到我的服务器

您将需要声明您的String dateStr private String mDateStr;

  protected Void doInBackground(Void... voids) {



            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                    DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z",Locale.ENGLISH);
                    mDateStr = response.getFirstHeader("Date").getValue();
                    Date startDate = df.parse(mDateStr);
                    mDateStr = String.valueOf(startDate.getTime()/1000);
                    //Here I do something with the Date String

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



            return null;
        }
.... it continues, thsi is an asynctask

答案 1 :(得分:0)

您必须拥有NTP服务器library。并将您的代码放入try方法中。希望它会奏效。 :)