Anna Anna - 6 months ago 12
Android Question

How to get time not from the System?

How can i get the current date and time?
Not like this way:

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

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


I do not want dependency of the system clock
It's mean if the user changed the date and time on his device the app will be shown the real time and not changes?


  • Do i need to use a server for this?

  • The app must be connected the internet?

  • There is library for this?


Answer
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 ""; //error
    }

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

note you will need to add the internet permission in the manifest if you haven't already