如何从系统中获取时间?

问题描述:

我怎样才能得到当前的日期和时间? 不喜欢这样的方式:如何从系统中获取时间?

Date date = new Date(); 
date.getTime(); 

Calendar cal = Calendar.getInstance(); 
cal.getTime(); 

我不希望系统时钟 的依赖性就这意思是,如果用户更改了日期和时间,他的设备上的应用程序将显示的实时性和不变化?

  • 我需要为此使用服务器吗?
  • 该应用程序必须连接到互联网?
  • 有这样的图书馆吗?
+0

您可以使用从服务器返回当前日期和时间 – Eenvincible

+1

的API(终点)我使用这个api来完成http://www.timeapi.org/。你不需要一台服务器,就像我刚发布的服务器一样。该应用程序必须连接到互联网,你不需要一个库,你可以使用本地网络apis到这 –

+0

@TomerShemesh你可以显示一些示例代码吗? – Anna

new AsyncTask<Void, Void, Long>() { 

    @Override 
    protected Long doInBackground() { 
     try { 
     JSONParser jParser = new JSONParser(); 
     JSONObject json = jParser.getJSONFromUrl("http://www.timeapi.org/utc/now.json?" + URLEncoder.encode("\Q")); 
     //gets time in UTC 
      return Long.parseLong(json.getString("dateString")); 
     } catch(Exception e){} 
     return -1; //error 
    } 

    @Override 
    protected void onPostExecute(Long date) { 
      //do whatever you want with your date in your app 
      //it will look like 1464039845096 
    } 
}.execute(); 

注意您需要添加Internet权限的清单,如果你还没有

+0

谢谢有一种方法来获得毫秒或只是在这种格式的时间? – Anna

+0

@Anna我改变了我的例子返回毫秒 –

+0

谢谢你,我最好的!你确定JSONParser有getJSONFromUrl方法吗? – Anna