1.最近在做系统时,突然发现浏览器时区与web服务器时区可能存在不同,这样就导致数据传输只能建立在UTC的基础上,那么应用服务器和web服务器也有可能不在同一个时区,所以数据库数据存的也是UTC时间。
这就涉及要各种本地时间转UTC时间,UTC时间转本地时间的问题了。
在这里必须说的一点就是,不管是服务器间通信,还是浏览器或者客户端与服务器间通信,都采用传参为utc时间+时区的方法,而且出于本人习惯,utc时间通常用字符串,方便传值,也因为字符串是没有任何时区瓜葛,是实实在在的。
2.想必大家都听过太多次 Date中不包含时区的说法,但是当我们这样写,想将一个UTC字符串转换成对应的Date时:
String dateStr = "2013-1-31 12:17:14"; //页面传进来的UTC时间
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date dateTmp = dateFormat.parse(dateStr);
System.out.println(dateTmp);
} catch (ParseException e) {
e.printStackTrace();
}
却发现打印出来是Thu Jan 31 12:17:14 CST 2013 和传入的字符串一致。 在我转换成UTC时间时,居然,减少了8个小时。也就是说我的UTC时间跟传进来的字符串完全不一样了。
赶紧百度查CST,确发现 CST可视为美国,澳大利亚或中国的标准时间 在这里,也就是说是中国标准时间的意思,那么所谓的不带时区呢,没想到你是这样的Date!
嗯,经过各种乱查,发现其实dateFormat有设置时区的功能,如果在上述第二行代码下加入这句话:
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
// dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
获取的Date再转换成UTC时间,与传进来的字符串一致。
我理解上面这句代码的意思为:告诉别人我的字符串是utc时间
那么同理,想要把Date转成对应的UTC字符串,要这样:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 告诉别人我要的字符串是utc时间
String str = sdf.format(date);
当然偶尔还有将UTC时间的字符串转换成浏览器/客户端的字符串的需求,这里一并写在下面。
/**
* 将utc的字符串转换成本地Date
*/
public static Date getUTCStrToLocalDate(String s) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 告诉别人我的字符串是utc时间
return sdf.parse(s);
}
/**
* 将Date变成UTC字符串
*/
public static String getUTCStrToLocalDate(Date d) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 告诉别人我的字符串是utc时间
return sdf.format(d);
}
/**
* 将UTC字符串变成浏览器端的相应时区的字符串
*/
public static String getUTCStrToBrowserStr(String s, String timeZone)throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // 告诉别人我的字符串是utc时间
Date date = sdf.parse(s);
sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); // 告诉别人我的字符串是utc时间
return sdf.format(date);
}