在工作中遇到一个问题
某一类数据在数据库中保存时,是根据伦敦时间保存的,也就是GMT+0
其他业务在使用时,需要根据用户的输入时间去查询,用户的时间参数中带有时区
例如:
time:17:30
timeZone:GMT+8
因此需要根据时区将用户带入的参数转化为GMT+0的时间,然后去查询,在来回折腾后使用如下代码可以实现
public class TimeZoneLearn
{
private static final String TIME_FORAMT = "yyyyMMdd'T'HHmmss'Z'";
private static final String TIME_ZONE = "GMT+8";
private static final String TIME_ZONE_ZERO = "GMT+0";
@Test
public void test() throws ParseException
{
Long time = getTime(new Date());
SimpleDateFormat foraDateFormat = new SimpleDateFormat(TIME_FORAMT);
String result = foraDateFormat.format(new Date(time));
System.out.println(result);
}
public Long getTime(Date date) throws ParseException
{
SimpleDateFormat formater = new SimpleDateFormat(TIME_FORAMT);
formater.setTimeZone(TimeZone.getTimeZone(TIME_ZONE_ZERO));
String time = formater.format(date);
formater.setTimeZone(TimeZone.getTimeZone(TIME_ZONE));
Date parse = formater.parse(time);
return parse.getTime();
}
}
只需将用户的时间转换为Date对象,传入getTime方法中,TIME_ZONE常量使用用户给定的时区即可