Java获取Ntp
服务器时间
package demo.test.ntp;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.apache.commons.net.ntp.TimeStamp;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class NtpTest {
public static void main_bak(String[] args) {
StringBuilder sb = new StringBuilder();
//sb.append("\n").append(" 11 MD5 Ib[:*M=OW4eDTxFk*`{I # MD5 key");//追加时使用
sb.append(" 11 MD5 Ib[:*M=OW4eDTxFk*`{I # MD5 key");
File conf = new File("C:\\Users\\EST\\Desktop\\ntp\\keys2");
try {
//FileUtils.writeStringToFile(conf, sb.toString(),true);//追加时使用
FileUtils.writeStringToFile(conf, sb.toString(),false);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
Date formDate = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).parse("Thu Feb 10 17:00:51 CST 2022");
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(formDate);
System.out.println(format);
Date formDate2 = new SimpleDateFormat("dd MMM HH:mm:ss", Locale.US).parse("10 Feb 16:46:06");
String format2 = new SimpleDateFormat("MM-dd HH:mm:ss", Locale.CHINA).format(formDate2);
System.out.println(format2);
Date formDate3 = new SimpleDateFormat("EEE, MMM dd yyyy HH:mm:ss.SSS", Locale.US).parse("Mon, Feb 14 2022 14:02:09.439");
String format3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(formDate3);
System.out.println(format3);
Date formDate4 = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS", Locale.US).parse("Feb 14 2022 14:02:09.439");
String format4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(formDate4);
System.out.println(format4);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(getDateTime("cn.pool.ntp.org"));
}
public static String getDateTime(String host) {
NTPUDPClient timeClient = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
timeClient = new NTPUDPClient();
timeClient.setDefaultTimeout(10000);
InetAddress timeServerAddress = InetAddress.getByName(host);
TimeInfo timeInfo = timeClient.getTime(timeServerAddress);
TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();
Date date = timeStamp.getDate();
//系统获取:Thu Feb 10 17:00:51 CST 2022
//服务器date命令查询:Thu Feb 10 17:00:51 CST 2022
//服务器ntpdate命令查询:10 Feb 16:46:06
return dateFormat.format(timeStamp.getDate());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (timeClient != null) {
timeClient.close();
}
}
return null;
}
}