`
tanzek
  • 浏览: 50416 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
社区版块
存档分类
最新评论

你的SimpleDateFormat起作用了吗?

阅读更多
通过SimpleDateFormat格式化日期输出是一种常见的用法,如下:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(
new Date()));
如果上述代码正常工作,它将显示当前的日期年月日时分秒格式。

但是有时候它并没有如我们预期的那样,而显示的时间比当前的时间少了八个小时,或是多了八个小时,而这一切就需要我们再关注另外一个问题,那就是时区(TimeZone)。
如果我们将时区进行设置为“东八区”,那么就一切回复正常了。如下有两种方式:

1、通过改变默认的时区
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8:00"));
SimpleDateFormat sdf 
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(Calendar.getInstance()));

2、通过设定SimpleDateFormat的构造参数
    通过查阅API手册,可知SimpleDateFormat还有一个构造函数:SimpleDateFormat(String pattern, Locale locale) ,因此我们就可通过设定Locale来取得特定时区的日期格式。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
System.out.println(sdf.format(new Date());

到这时候,关于时区的简单设定就结束了,更多的参考请在网上搜索关于Java Locale的设定文章。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics