天天看點

擷取NTP時間伺服器時間

public static String getNTPServerDateTime(String NTPTimeServerUrl) {
    String dateTimeMessage;
    try {
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress timeServerAddress = InetAddress.getByName(NTPTimeServerUrl);
        TimeInfo timeInfo = timeClient.getTime(timeServerAddress);
        TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
        Date date = timeStamp.getDate();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        dateTimeMessage = dateFormat.format(date);
    } catch (UnknownHostException e) {
        return e.getMessage();
    } catch (IOException e) {
        return e.getMessage();
    }
    return dateTimeMessage;

}





       
NTPTimeServerUrl為NTP伺服器位址,如上海交通大學網絡中心NTP伺服器位址為:202.120.2.101      

繼續閱讀