java linux runtime 正则表达式_3、java设置Linux系统时间之 正则表达式解析时间 及总结...

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、将这段时间做的东西记录下来,希望以后能够少走弯路。功能不大,但也涉及到了几个知识点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值