Skip to content Skip to sidebar Skip to footer

3.in.pool.ntp.org Sometimes Fails To Return Date In Android Device

I am fetching UTC date from ntp servers from a long time now. But I have noticed that I am getting empty string sometimes(once in 100 times) as I run my code. My code is DateFormat

Solution 1:

Better try this Class to get the right UTC Time from NTP Server:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


classNTP_UTC_Time
{
privatestaticfinalStringTAG="SntpClient";

privatestaticfinalintRECEIVE_TIME_OFFSET=32;
privatestaticfinalintTRANSMIT_TIME_OFFSET=40;
privatestaticfinalintNTP_PACKET_SIZE=48;

privatestaticfinalintNTP_PORT=123;
privatestaticfinalintNTP_MODE_CLIENT=3;
privatestaticfinalintNTP_VERSION=3;

// Number of seconds between Jan 1, 1900 and Jan 1, 1970// 70 years plus 17 leap daysprivatestaticfinallongOFFSET_1900_TO_1970= ((365L * 70L) + 17L) * 24L * 60L * 60L;

privatelong mNtpTime;

publicbooleanrequestTime(String host, int timeout) {
    try {
        DatagramSocketsocket=newDatagramSocket();
        socket.setSoTimeout(timeout);
        InetAddressaddress= InetAddress.getByName(host);
        byte[] buffer = newbyte[NTP_PACKET_SIZE];
        DatagramPacketrequest=newDatagramPacket(buffer, buffer.length, address, NTP_PORT);

        buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

        writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

        socket.send(request);

        // read the responseDatagramPacketresponse=newDatagramPacket(buffer, buffer.length);
        socket.receive(response);          
        socket.close();

        mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);            
    } catch (Exception e) {
      //  if (Config.LOGD) Log.d(TAG, "request time failed: " + e);returnfalse;
    }

    returntrue;
}


publiclonggetNtpTime() {
    return mNtpTime;
}


/**
 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
 */privatelongread32(byte[] buffer, int offset) {
    byteb0= buffer[offset];
    byteb1= buffer[offset+1];
    byteb2= buffer[offset+2];
    byteb3= buffer[offset+3];

    // convert signed bytes to unsigned valuesinti0= ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
    inti1= ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
    inti2= ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
    inti3= ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

    return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
}

/**
 * Reads the NTP time stamp at the given offset in the buffer and returns 
 * it as a system time (milliseconds since January 1, 1970).
 */privatelongreadTimeStamp(byte[] buffer, int offset) {
    longseconds= read32(buffer, offset);
    longfraction= read32(buffer, offset + 4);
    return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);        
}

/**
 * Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900
 */privatevoidwriteTimeStamp(byte[] buffer, int offset) {        
    intofs=  offset++;

    for (int i=ofs;i<(ofs+8);i++)
      buffer[i] = (byte)(0);             
}

}

And use it with:

longnow=0;

        NTP_UTC_Timeclient=newNTP_UTC_Time();

        if (client.requestTime("pool.ntp.org", 2000)) {              
          now = client.getNtpTime();
        }

If you need UTC Time "now" as DateTimeString use function:

private String get_UTC_Datetime_from_timestamp(long timeStamp){

    try{

        Calendarcal= Calendar.getInstance();
        TimeZonetz= cal.getTimeZone();

        inttzt= tz.getOffset(System.currentTimeMillis());

        timeStamp -= tzt;

        // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());DateFormatsdf=newSimpleDateFormat();
        DatenetDate= (newDate(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return"";
     }
    } 

and use it with:

StringUTC_DateTime= get_UTC_Datetime_from_timestamp(now);

Post a Comment for "3.in.pool.ntp.org Sometimes Fails To Return Date In Android Device"