DateFormat 与 TimeZone

DateFormat 是日期/时间格式化子类的抽象类,它的实现类提供了很多种日期格式化的方法对日期解析和格式化。
TimeZone 表示时区偏移量,接受时区ID,例如:Asia/Shanghai或者GMT+8,根据时区ID获取时区偏移量

DateFormat提供一个方法,setTimeZone(TimeZone zone),接受时区偏移量作为传入参数,为DateFormat日历设置时区,默认情况使用Locale.getDefault()中的本地时区。
SimpleDateFormat timeZoneFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
参考public SimpleDateFormat(String pattern){this(pattern,Locale.getDefault());}


DateFormat常用的parse(String source)和format(Date date) 方法,默认情况下使用本地时区进行解析和格式化时间,如果在解析或者格式化之前,强制设置了时区,则采用设置好的时区进行解析和格式化时间。
SimpleDateFormat timeZoneFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
timeZoneFormat.parse("2011-06-29 14:44:25"); //解析成"Asia/Shanghai"时区时间
timeZoneFormat.format(new Date()); // 格式化成"Asia/Shanghai"时区时间


以format为例,format接受 本地时间作为传入参数,计算DateFormat设置的时区与本地时区的时间偏移量(即时差),最终将本地时间格式化成指定时区的时间(parse亦然)

猜你喜欢

转载自dmouse.iteye.com/blog/1109391