如何在Java中设置默认时区并控制日期存储在数据库中的方式? [英] How to set default time zone in Java and control the way date are stored on DB?
问题描述
我遇到以下问题,当我将我的webapp的战争安装在虚拟linux服务器上时出现了这个问题。这里是:我的服务器系统时间似乎是正确的,实际上在shell上输入日期出来:
Mon Apr 11 11: 47:30 CEST 2011
这是我的挂钟时间。即使mysql工作正常,如果我选择now(),我会得到:
mysql>选择now()
- > ;
+ --------------------- +
| now()|
+ --------------------- +
| 2011-04-11 11:52:57 |
+ --------------------- +
1行(0.01秒)
但是我的应用程序(Java6 + tomcat 6上的Spring + hibernate)会将每个日期保存在带有GMT时区的数据库中(并且时间正确地用与格林威治标准差,这是很好的)。现在的问题是,我得到的所有日期显示格林尼治标准时间,即使我这样做:
$ p $ 静态最终DateFormat格式=新SimpleDateFormat(
dd / MM / yyyy'alle'HH:mm,Locale.ITALY);
我没有正确抵消小时数,但它们保持在GMT时间,如果我将Z(显示时区)放在模式中。
在Windows下,我的日期值存储在mySQL的本地时区中。所以在我开发的Windows机器上,我将在CEST中拥有所有的日期。这很烦人,因为我不知道如何预测系统的行为方式,我必须进行无聊的测试并弄清楚如何改变这种情况。
你有没有看过这个问题?如何处理它?</ p>
SimpleDateFormat sf1 = new SimpleDateFormat(dd / MM / yyyy'alle'HH:mm:ss);
sf1.setTimeZone(TimeZone.getTimeZone(Europe / Rome));
System.out.println(sf1.format(new Date()));
//列出所有时区
System.out.println(Arrays.asList(TimeZone.getDefault()));
I've the following problem, that showed up when I installed my webapp's war on a virtual linux server. Here it is: my server system time seems correct, in fact typing date on shell comes out with:
Mon Apr 11 11:47:30 CEST 2011
which is my "wall clock time". Even mysql works fine, if I do select now(), I get:
mysql> select now()
-> ;
+---------------------+
| now() |
+---------------------+
| 2011-04-11 11:52:57 |
+---------------------+
1 row in set (0.01 sec)
But my application (Spring+hibernate on Java6 + tomcat 6) will save every date on DB with a GMT timezone (and the time is correctly offset with the difference from GMT, which is good). Now the problem is that I get all dates displayed with GMT, even if I do:
static final DateFormat format = new SimpleDateFormat(
"dd/MM/yyyy 'alle' HH:mm", Locale.ITALY);
I don't get the hours correctly offset, but they remain in GMT and they display GMT if I put Z (that displays timezone) in the pattern.
Under Windows instead I had date values stored in my native timezone on mySQL. So on my windows machine where I develop I will have all the dates in CEST. This is annoying as I don't know how to predict the way the system will behave and I have to do boring tests and figure out how to change this.
Do you have ever seen this problem? How to deal with it?
SimpleDateFormat sf1 = new SimpleDateFormat("dd/MM/yyyy 'alle' HH:mm:ss");
sf1.setTimeZone(TimeZone.getTimeZone("Europe/Rome"));
System.out.println(sf1.format(new Date()));
// List all Timezone
System.out.println(Arrays.asList(TimeZone.getDefault()));
这篇关于如何在Java中设置默认时区并控制日期存储在数据库中的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!