I'm trying to get time from the ntp server, but for some reason I only get the current device time. Took this question .

public Calendar getCurrentDate(){ Date date = new Date(); Calendar cal = new GregorianCalendar(); try{ String timeServer = "0.pool.ntp.org"; NTPUDPClient timeClient = new NTPUDPClient(); InetAddress inetAddress = InetAddress.getByName(timeServer); TimeInfo timeInfo = timeClient.getTime(inetAddress); long time = timeInfo.getMessage().getReceiveTimeStamp().getTime(); Log.i("m", String.valueOf(time)+" " + timeInfo); cal.setTimeInMillis(time); } catch(Exception e){ e.printStackTrace(); } return cal; } 

but in the end I get:

 1552491732 1552491732 

where the first number is what the / 1000 method returned, and the second number is System.currentTimeMillis()/1000 I already shoveled a lot of literature and sources, but my program persistently gives me time on the device, not the current timestamp time. I can not understand what I am doing wrong. It seems to do everything as in the answer. If someone has a working method of how to get the time and date in the ntp server, I would be very grateful if you share :)

    1 answer 1

    Here is what I did to get the ntp server time:

    1. Found libu - implementation 'com.github.medavox:MuTime:0.5'
    2. Made a class:

       class MyTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { // TODO Auto-generated method stub //optionally enable the disk cache MuTime.enableDiskCaching(Objects.requireNonNull(getContext()));//this hardens MuTime against clock changes and reboots try { MuTime.requestTimeFromServer("time.google.com"); } catch (IOException e) { e.printStackTrace(); } try { long theActualTime = MuTime.now();//throws MissingTimeDataException if we don't know the time } catch (MissingTimeDataException e) { Log.i("m", "failed to get the actual time:+e.getMessage()"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); } } 
    3. Calling class:

       mt = new MyTask(); mt.execute(); 
    4. I get time)

    Maybe someone will come in handy.