ElasticSearch7.0.0 导入时间多8个小时问题
问题原因:elasticsearch 内部存储时间是按照UTC的标准时间存储的,而我本地是GMT+8时区,因此存储到es的时候需要将时间转成UTC来存储。
解决方式:
-
对于读取字符串需要SimpleDateFormat转换的,默认的时区是GMT+8,format的时候需要设置时区
//读取字符串解析成date的时候用GMT+8:00 //format成字符串时用GMT+0:00 String dateString = "2020-4-22 10:25:34"; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("GMT+8:00")); Date date = df.parse(dateString); df.setTimeZone(TimeZone.getTimeZone("GMT+0:00")); dateString = df.format(date);
SimpleDateFormat设置时区
设置时区有以下三种写法,格式化后的时间是一样的
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
System.out.println("方法一:" + dateFormat.format(new Date()));
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
System.out.println("方法二:" + dateFormat.format(new Date()));
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
System.out.println("方法三:" + dateFormat.format(new Date()));