16

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!!

Community
  • 1
  • 1
MW_hk
  • 1,181
  • 4
  • 14
  • 39
  • 1
    Have you done any research yourself regarding this? There are many implementations out there in similar languages without any use of heavyweight external libraries. Take a look at this example http://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-c – az4dan May 28 '13 at 09:08
  • 1
    Please vote again for the post..... I am asking about Android programming.... I want to know if there is already any functions in Android that I could use or I simply have to import a library.... Android programming is different from what you sugguested – MW_hk May 28 '13 at 09:45

1 Answers1

24

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());
    }
});
Googlian
  • 6,077
  • 3
  • 38
  • 44
MW_hk
  • 1,181
  • 4
  • 14
  • 39
  • hi i need your help on date and time getting using NTP. Can you help me? – SathishKumar Apr 04 '14 at 09:30
  • You need to set up a time server on any PC or device and then include the ntpclient library in your application, then you could query the time from the time server from your application.... – MW_hk Apr 07 '14 at 00:22
  • I'm always obtaining timeout exception. What timeout did you used @user1702061 ? – csfb Jan 05 '15 at 21:05
  • 1
    Is it that your server had no response on the request? (erm.... I actually had never got any timeout exception @-@..) – MW_hk Jan 09 '15 at 00:13
  • 1
    it alway return current system time, what wrong? – vuhung3990 Jan 18 '15 at 15:39