Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default time zone in Java and control the way date are stored on DB?

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?

like image 478
gotch4 Avatar asked Nov 29 '25 01:11

gotch4


2 Answers

DateFormat does support a notion of time zone. Add something like:

format.setTimeZone(TimeZone.getTimeZone("Europe/Rome");
like image 184
philwb Avatar answered Nov 30 '25 13:11

philwb


  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()));
like image 29
Dead Programmer Avatar answered Nov 30 '25 14:11

Dead Programmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!