开发者

how to make my java app get global time from some online clock [duplicate]

This question already has answers here: Java: Get current Date and Time from Server not System clock (3 answers) Closed开发者_开发知识库 last year.

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?


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


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);
}
}


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());
...


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?");
    }

  }



}


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());
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜