Anna
Anna

Reputation: 499

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?

Upvotes: 1

Views: 268

Answers (1)

Tomer Shemesh
Tomer Shemesh

Reputation: 13345

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();

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

Upvotes: 2

Related Questions