The result of Java new Date() don't match the system time

Linux系统下,Java new Date()获取时间与系统时间不符

1.Description of the problem

A function which is desigined to query the summary of rain was reported a bug in the system which applied in a linux server,for it didn’t have same result with the completely saome application which applied in a windows server .

2.Analysis of the problem

The first thing occured in my mind is to analyze the difference of these two environments.The application was deployed by one war package,so i checked the java version by java -version and they are both Oracle JDK1.7.0_79,and then tomcat version are proved to be same.

The following thing should be analyze the process how data flows.The two application fetch data from the same database , the bug report meant there is a wrong statistic result shown on the page.So,the probem can be navigated to the Datebase query part in the dao code,the desensitization code are displayed below:

SimpleDateFormat h = new SimpleDateFormat("yyyy-MM-dd HH");
Date d = new Date();
String start = h.format(d) + ":00:00";
String end   = h.format(new Date(d.getTime() + 3600000L)) + ":00:00";
String sql   ="select * from table where time>= ? and time <? and .....";
ps.setString(1,start);
ps.setString(2,end);

After read the code, a assumption occurs,which start time or end time are different in the two environments.

3.Reappearance of the problem

To vertify the assumption,we need to write a code , compile and run in different environment.Here it goes the code and opertions

import java.text.SimpleDateFormat;
import java.util.Date;

public class main {
    public static void main(String[] args) {
        SimpleDateFormat h = new SimpleDateFormat("yyyy-MM-dd HH");
        Date d = new Date();
        String lt1 = h.format(new Date(d.getTime())) + ":00:00";
        String lt2 = h.format(new Date(d.getTime() + 3600000L)) + ":00:00";
        System.out.println(lt1);
        System.out.println(lt2);
    }
}
  • windows
javac main.java
java main

2018-08-09 19:00:00
2018-08-09 20:00:00
  • linux
javac main.java
java main

2018-08-09 11:00:00
2018-08-09 12:00:00

The following attemp is check the date in different environment,and the code are shown below

import java.util.Date;

public class main {
    public static void main(String[] args) {
        System.out.println(new Date());
    }
}
  • windows
Thu Aug 09 20:08:48 CST 2018
  • linux
Thu Aug 09 12:08:52 GMT 2018

Solution of the problem

The cause of the problem is that the timezone of jvm is different from the operation system,which is 8 hour,so we can change the timezone of jvm into GMT+8 by add following in jvm config

Dfile.encoding=UTF8    
-Duser.timezone=GMT+08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值