28560

3.in.pool.ntp.org sometimes fails to return date in android device

Question:

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 outputFormat = new SimpleDateFormat("dd-MM-yyyy"); SntpClient client = new SntpClient(); if (client.requestTime("3.in.pool.ntp.org", 10000)) { Date actualD = new Date(client.getNtpTime()); actualDate = outputFormat.format(actualD).trim(); }

Can u suggest me some situation where this code has its limitations. And can this limitation be overcome if I use <strong>pool.ntp.org</strong> instead of <strong>3.in.pool.ntp.org</strong>

Answer1:

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; class NTP_UTC_Time { private static final String TAG = "SntpClient"; private static final int RECEIVE_TIME_OFFSET = 32; private static final int TRANSMIT_TIME_OFFSET = 40; private static final int NTP_PACKET_SIZE = 48; private static final int NTP_PORT = 123; private static final int NTP_MODE_CLIENT = 3; private static final int NTP_VERSION = 3; // Number of seconds between Jan 1, 1900 and Jan 1, 1970 // 70 years plus 17 leap days private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L; private long mNtpTime; public boolean requestTime(String host, int timeout) { try { DatagramSocket socket = new DatagramSocket(); socket.setSoTimeout(timeout); InetAddress address = InetAddress.getByName(host); byte[] buffer = new byte[NTP_PACKET_SIZE]; DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT); buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3); writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET); socket.send(request); // read the response DatagramPacket response = new DatagramPacket(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); return false; } return true; } public long getNtpTime() { return mNtpTime; } /** * Reads an unsigned 32 bit big endian number from the given offset in the buffer. */ private long read32(byte[] buffer, int offset) { byte b0 = buffer[offset]; byte b1 = buffer[offset+1]; byte b2 = buffer[offset+2]; byte b3 = buffer[offset+3]; // convert signed bytes to unsigned values int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0); int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1); int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2); int i3 = ((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). */ private long readTimeStamp(byte[] buffer, int offset) { long seconds = read32(buffer, offset); long fraction = 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 */ private void writeTimeStamp(byte[] buffer, int offset) { int ofs = offset++; for (int i=ofs;i<(ofs+8);i++) buffer[i] = (byte)(0); } }

And use it with:

long now = 0; NTP_UTC_Time client = new NTP_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{ Calendar cal = Calendar.getInstance(); TimeZone tz = cal.getTimeZone(); int tzt = tz.getOffset(System.currentTimeMillis()); timeStamp -= tzt; // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault()); DateFormat sdf = new SimpleDateFormat(); Date netDate = (new Date(timeStamp)); return sdf.format(netDate); } catch(Exception ex){ return ""; } }

and use it with:

String UTC_DateTime = get_UTC_Datetime_from_timestamp(now);

Recommend

  • Regarding starting the threads on a condition
  • Simple linked list-C
  • SQLite connection strategies
  • How to calculate the camera position from Vuforia GL matrix?
  • Linq Merge lists
  • Checking if an array in C is symmetric
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • Reduction and collapse clauses in OMP have some confusing points
  • Appending Character to Character Array In C
  • OOP Javascript - Is “get property” method necessary?
  • GridView breaks while scrolling
  • copying resource to sdcard gives a damaged file in android
  • Database structure design with variable amounts of fields
  • how to adjust image in a panel in Java swing?
  • Ajax Loaded meta Tags
  • Get one-time binding to work for ng-if
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • req.body is undefined - nodejs
  • Problems to linebreak with an int in JLabel
  • How reduce the height of an mschart by breaking up the y-axis
  • Volley JsonObjectRequest send headers in GET Request
  • Possible to stop flickering java tooltip in heavyweight mode?
  • output of program is not same as passed argument
  • MySQL WHERE-condition in procedure ignored
  • sending/ receiving email in Java
  • How to set my toolbar fixed while scrolling android
  • Importing jscolor library in angular 2
  • Rearranging Cells in UITableView Bug & Saving Changes
  • AT Commands to Send SMS not working in Windows 8.1
  • How to delete a row from a dynamic generate table using jquery?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper way to use connect-multiparty with express.js?
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • JTable with a ScrollPane misbehaving
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • apache spark aggregate function using min value
  • Checking variable from a different class in C#
  • Easiest way to encapsulate a HTML5 webpage into an android app?
  • Sorting a 2D array using the second column C++
  • java string with new operator and a literal