通过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的设定文章。
分享到:
相关推荐
有关SimpleDateFormat的常用方法说明
JavaScript实现的java.text.SimpleDateFormat。希望多多交流。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); date.setTime(time); System.out.println(sdf.format(date)); 发现时间于想要的时间不符,请运行Time.reg文件
日期操作。。。基础的SimpleDateFormat格式化日期!!操作!》初级学习代码
由浅入深解析 SimpleDateFormat 由浅入深解析 SimpleDateFormat
SimpleDateFormat使用详解。非常实用!!!!
java 使用SimpleDateFormat类获取系统的当前时间 java 使用SimpleDateFormat类获取系统的当前时间
高并发之-SimpleDateFormat类的线程安全问题和解决方案.docx
目录SimpleDateFormat诡异bug复现SimpleDateFormat诡异bug字符串日期转Date日期(parse)Date日期转String类型(format)SimpleDateFormat出现bug的原因如何解决SimpleDateFormat多线程安全问题局部变量使用...
深入理解Java:SimpleDateFormat安全的时间格式化
1.创建SimpleDateFormat对象,确定日期被格式化的格式 2.使用循环,在循环中调用Thread的sleep方法,让线程休眠1s后打印当前时间的字符串
NULL 博文链接:https://qinchaoyong.iteye.com/blog/543109
NULL 博文链接:https://chaoyi.iteye.com/blog/2082317
NULL 博文链接:https://flynndang.iteye.com/blog/711878
主要介绍了Java多线程环境下SimpleDateFormat类安全转换,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
SimpleDateFormat 是一个以国别敏感的方式格式化和分析数据的具体类。这篇文章主要介绍了Java中的SimpleDateFormat使用详解,需要的朋友可以参考下
SimpleDateFormat里面对应格式化输出的模式字母
主要为大家详细介绍了Java中SimpleDateFormat的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
SimpleDateFormat线程不安全的5种解决方案.md