设置项目时区
/**
* @ClassName:UTCTimeZoneConfiguration
* @Description: 统一时区设定,在项目初始化时设置当前进程的默认时区
* @Author:qym
* @Date:2020/7/28 10:23
*/
@Configuration
public class UTCTimeZoneConfiguration implements ServletContextListener {
private static String timeZoneId;
public static String getTimeZoneId() {
return timeZoneId;
}
@Value("${time.zone.id:}")
public void setTimeZoneId(String timeZoneId) {
this.timeZoneId = timeZoneId;
}
public void contextInitialized(ServletContextEvent event) {
System.setProperty("user.timezone", timeZoneId);
TimeZone.setDefault(TimeZone.getTimeZone(timeZoneId));
}
public void contextDestroyed(ServletContextEvent event) {}
}
配置文件配置时区
#GMT+8 配置时区,控制前端显示的时间
spring.jackson.time-zone=GMT-7
#项目初始化时设置当前进程的默认时区,与jackson.time-zone及数据库的时区保持一致 Asia/Shanghai(GMT+8) America/Los_Angeles(GMT-7)
time.zone.id=GMT-7
配置数据库时区
#Timezone=GMT-7是时区
spring.datasource.url=jdbc:mysql://localhost:3306/vrs_test2?serverTimezone=GMT-7&characterEncoding=utf-8
UTC转换为本地时间
/**
* @description: utc转换为本地时间
* @params:
* @return:
* @author: fanwj
* @Date: 2020/7/31 15:13
*/
public static Date utcToLocal(String utcTime){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcDate = null;
try {
utcDate = sdf.parse(utcTime);
} catch (ParseException e) {
throw new JrsfServiceException(110,"The time format is wrong, please input yyyy-MM-dd HH:mm:ss");
}
sdf.setTimeZone(TimeZone.getDefault());
Date locatlDate = null;
String localTime = sdf.format(utcDate.getTime());
System.out.println(TimeZone.getDefault());
try {
locatlDate = sdf.parse(localTime);
System.out.println(localTime);
} catch (ParseException e) {
e.printStackTrace();
}
return locatlDate;
}
本地时间转换为UTC时间
/**
*
* <p>Description: 本地时间转化为UTC时间</p>
* @param localTime
* @return
* @author wgs
* @date 2018年10月19日 下午2:23:43
*
*/
public static Date localToUTC(String localTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date localDate= null;
try {
localDate = sdf.parse(localTime);
} catch (ParseException e) {
e.printStackTrace();
}
long localTimeInMillis=localDate.getTime();
/** long时间转换成Calendar */
Calendar calendar= Calendar.getInstance();
calendar.setTimeInMillis(localTimeInMillis);
/** 取得时间偏移量 */
int zoneOffset = calendar.get(java.util.Calendar.ZONE_OFFSET);
/** 取得夏令时差 */
int dstOffset = calendar.get(java.util.Calendar.DST_OFFSET);
/** 从本地时间里扣除这些差量,即可以取得UTC时间*/
calendar.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
/** 取得的时间就是UTC标准时间 */
Date utcDate=new Date(calendar.getTimeInMillis());
return utcDate;
}