1、Linux主机时间同步
Linux主机时间同步一般是通过Linux的Cron + ntp命令实现的,不需要java编程。
我遇到的是一个特殊的情况,所以采用了编程方法实现。
访问网络时间服务器,获取时间是采用普通的socket编程实现的。
常用的时间服务器如下:
time.nist.gov
time-a.nist.gov
time-b.nist.gov
time-nw.nist.gov
以time.nist.gov 为例:
Socket s = new Socket(server, port);
StringBuffer sb = new StringBuffer();
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
byte[] b = new byte[10];
while(bis.read(b) != -1) {
sb.append(new String(b));
}
返回值如下sb.toString() :
54994 09-06-12 06:32:42 50 0 0 710.4 UTC(NIST) * (包含回车换行)
所以要通过这则表达式提取相关的 年、月、日、时、分、秒
然后将提取的值 通过SimpleDateFormat 转成本地时间,会有时区的转换问题:
Calendar 、DateFormat 都有TimeZone。
优先级:DateFormat > Calendar,也就是说最终的结果输出是根据DateFormat的TimeZone决定的。
2、时间解析部分的代码:
matches是将整个输入串与模式匹配,find是查找输入串中与模式匹配的子串
/*
* 解析获取获取的Internet时间
* @param time /r/n54964 09-05-13 07:27:25 50 0 0 598.3 UTC(NIST)/r/n(NIST)
*/
public void parseTime(final String time) throws APIException {
logger.debug("解析时间:" + time);
Matcher serverTimeMatcher = Pattern.compile("[0-9]{2,4}-[0-9]{2}-[0-9]{2} *[0-9]{2}:[0-9]{2}:[0-9]{2}").matcher(time);
if(time != null && !time.equals("") && serverTimeMatcher.find()){
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd hh:mm:ss");//服务器时间格式化
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));//时间服务器的时区,一般时间服务器返回的时间是格林威治时间,GMT
SimpleDateFormat sdfDate = new SimpleDateFormat("yy-MM-dd");//日期格式化
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");//时间格式化,如果为hh:mm:ss,时间为12h制
sdfDate.setTimeZone(TimeZone.getTimeZone("GMT+8"));
sdfTime.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Calendar cal = null;
try {
sdf.parse(serverTimeMatcher.group());
cal = sdf.getCalendar();
} catch (ParseException e) {
logger.error("InetTimeAccessService.parseTime解析时间错误",e);
throw new APIException("InetTimeAccessService.parseTime解析时间错误:"+e.getMessage());
}
//cal.setTimeZone(TimeZone.getTimeZone("GMT-8"));//如果存在DateFormat, cal设置时区无用
System.out.println("格式化:" + sdf.format(cal.getTime()));
System.out.println("格式化Date:" + sdfDate.format(cal.getTime()));
System.out.println("格式化Time:" + sdfTime.format(cal.getTime()));
}
else
throw new APIException("LanTimeAccessService.parseTime解析时间错误:" + time);
}
3、将这段时间做的东西记录下来,希望以后能够少走弯路。功能不大,但也涉及到了几个知识点。