日期在Linux与Windows下的区别

最近遇到了这个问题,就是相同的代码在Windows与Linux下的日期转换不一致。

原因:时区问题,主要是操作系统与JVM中的时区不同导致的

 

在网上查了很多处理的方法:最后总结出一条简单粗暴的方法;原理很简单,就是将要转换的日期转换成“GMT+8”,然后统一转换成String,再将String统一转换成时间戳,这样相应的时间差就不变了。

 1     public MonitorBean findByCity(String city) {
 2         int code = -1;
 3         SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd"); // 规定日期格式
 4         formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
 5         String tableName = "shop_queue_" + formatter.format(new Date());
 6         String sql = "select crawled_at from " + tableName + " where city = \"" + city + "\"" + " order by id desc limit 1;";
 7         try {
 8             Connection connection = dataSource.getConnection();
 9             Statement statement = connection.createStatement();
10             ResultSet resultSet = statement.executeQuery(sql);
11             if (resultSet.next()) {
12                 Timestamp timestamp = resultSet.getTimestamp(1);
13                 String timestampString = timestamp.toString().substring(0,timestamp.toString().length()-2);
14 
15                 SimpleDateFormat formatNowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 规定日期格式
16                 formatNowTime.setTimeZone(TimeZone.getTimeZone("GMT+8"));
17                 String nowTimeString = formatNowTime.format(new Date());
18                 try{
19                     long timeStamp = formatNowTime.parse(timestampString).getTime();
20                     long nowTime = formatNowTime.parse(nowTimeString).getTime();
21                     long value =  nowTime - timeStamp;
22                     if (value < Integer.valueOf(MAX_MIN) * 60 * 1000) {
23                         code = 100;
24                     }else {
25                         code = 200;
26                     }
27                 }catch (Exception e){
28                     e.printStackTrace();
29                     MonitorBean monitorBean = new MonitorBean(city, "-1", e.getMessage());
30                     return monitorBean;
31                 }
32             }
33             resultSet.close();
34             connection.close();
35             if(code > 0){
36                 return new MonitorBean(city, String.valueOf(code), city+"超出" + MAX_MIN + "分钟无数据");
37             }else{
38                 return new MonitorBean(city, String.valueOf(code), city+"无数据");
39             }
40         } catch (SQLException e) {
41             e.printStackTrace();
42             MonitorBean monitorBean = new MonitorBean(city, "-1", e.getMessage());
43             return monitorBean;
44         }
45     }

中间还遇到了查询MySQL出现后缀.0的情况,这个.0代表的是毫秒;

今天科大60周年庆,就在这里默默的祝福科大;有点想苏大了。

posted @ 2018-09-20 15:20  JayInnn  阅读(995)  评论(0编辑  收藏  举报