6

I am making a distributed java app for which I need both parts of the app to run on one standard time. Since system times can be different I was thinking if java API contains some class to download time from a standard online source?

n0ob
  • 1,275
  • 8
  • 20
  • 23

5 Answers5

5

You need to use the NTP (Network Time Protocol):

http://en.wikipedia.org/wiki/Network_Time_Protocol

The following link contains some reference Java NTP Client code for interacting with an NTP server:

http://psp2.ntp.org/bin/view/Support/JavaSntpClient

JetStream
  • 809
  • 1
  • 8
  • 28
Jonathan Holloway
  • 62,090
  • 32
  • 125
  • 150
4

Here is a code i found somewhr else.. and i am using it. this uses apache commons library.

// List of time servers: http://tf.nist.gov/service/time-servers.html

   import java.net.InetAddress;
   import java.util.Date;
   import org.apache.commons.net.ntp.NTPUDPClient;
   import org.apache.commons.net.ntp.TimeInfo;

    public class TimeLookup {
    public static final String TIME_SERVER = "time-a.nist.gov";

public static void main(String[] args) throws Exception {
    NTPUDPClient timeClient = new NTPUDPClient();
    InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
    TimeInfo timeInfo = timeClient.getTime(inetAddress);
    long returnTime = timeInfo.getReturnTime();
    Date time = new Date(returnTime);
    System.out.println("Time from " + TIME_SERVER + ": " + time);
}
}
Anshul Parashar
  • 3,096
  • 4
  • 30
  • 56
ChAnDu353
  • 541
  • 7
  • 11
2

pay attention .... timeInfo.getReturnTime() does not return the current time from the timeserver. it returns the local time when the request to the server was made.

after calling timeInfo.computeDetails() it's possible to get the offset by timeInfo.getOffset(). this returns the offset of the local time in millisecond.

to calculate the current time you could do something like:

...
long systemtime = System.currentTimeMillis();
Date realdate = new Date(systemtime + timeInfo.getOffset());
...
Rajendra_Prasad
  • 1,300
  • 4
  • 18
  • 36
user1727870
  • 121
  • 7
1
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;


public class TimeValidationHook {

  private static String getServerHttpDate(String serverUrl) throws IOException {
    URL url = new URL(serverUrl);
    URLConnection connection = url.openConnection();

    Map<String, List<String>> httpHeaders = connection.getHeaderFields();

    for (Map.Entry<String, List<String>> entry : httpHeaders.entrySet()) {
      String headerName = entry.getKey();
      if (headerName != null && headerName.equalsIgnoreCase("date")) {
        return entry.getValue().get(0);
      }
    }
    return null;
  }

  public static void main(String[] args) throws IOException {

    String serverUrl = args.length > 0 ? args[0] : "https://www.google.co.in";
    System.out.println(getServerHttpDate(serverUrl));
    Timestamp ts = new Timestamp(System.currentTimeMillis());
    System.out.println(ts);

//formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US)    Tue, 24 Jul 2018 13:25:37 GMT
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);

    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    Date date2 = null;
    Date date1 = null;
        try
        {
            date1. = sdf.parse(getServerHttpDate(serverUrl));
            date2 = sdf2.parse(ts.toString());
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }

        System.out.println("date1 : " + sdf2.format(date1));
    System.out.println("date2 : " + sdf2.format(date2));

    if (date1.compareTo(date2) > 0) {
        System.out.println("Date1 is after Date2"); 

        List<String> cmd = new ArrayList<String>();
        cmd.add("hg rollback");
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.directory(new File("E:\\repos\\Trunk"));
        Process p = pb.start();
    } else if (date1.compareTo(date2) < 0) {
        System.out.println("Date1 is before Date2");
    } else if (date1.compareTo(date2) == 0) {
        System.out.println("Date1 is equal to Date2");
    } else {
        System.out.println("How to get here?");
    }

  }



}
Dupinder Singh
  • 7,175
  • 6
  • 37
  • 61
0

Thanks Rajendra_Prasad that's true

public static void main(String[] args) throws Exception {
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        long returnTime = timeInfo.getReturnTime();
        Date time = new Date(returnTime);
        long systemtime = System.currentTimeMillis();
        timeInfo.computeDetails();
        Date realdate = new Date(systemtime + timeInfo.getOffset());
        System.out.println("Time from " + TIME_SERVER + ": " + time);
        System.out.println("Time from " + TIME_SERVER + ": " + realdate);
        System.out.println(""+time.getTime());
    }
  • 1
    Replying to people in answers in this manner is kind of unhelpful. It's really unclear exactly what you're saying is 'true' here, and without knowing that, all that's left is the block of code without explanation. – Mark Amery Oct 05 '13 at 22:28
  • This is the real answer – salih kallai Jan 19 '19 at 12:35