Pergunta

I would like to obtain the date and time from my own time server (i.e. 192.168.1.X) for the use inside my Android application

I have searched in the web and there are two solutions:

solution 1

solution 2

However, I was wonder if there is any solution without importing any libraries?

Thanks!!

Foi útil?

Solução

I end up using this one.

Create another class and then add the code inside. And then calling the class from my main activity to obtain the date.

The code is a bit old and I modified it by adding AsyncTask... works fine for me...

And one more thing, the usage of the class (from what the code sugguest) gives String.valueof(now) returns 0. Date should be used as below:

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

Updated: 2019-11-06

Use the latest SntpClient library from here https://github.com/aslamanver/sntp-client-android

Retrieve the time of a specific time zone.

SNTPClient.getDate(TimeZone.getTimeZone("Asia/Colombo"), new SNTPClient.Listener() {
    @Override
    public void onTimeReceived(String rawDate) {
        // rawDate -> 2019-11-05T17:51:01+0530
        Log.e(SNTPClient.TAG, rawDate);
    }

    @Override
    public void onError(Exception ex) {
        Log.e(SNTPClient.TAG, ex.getMessage());
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top