Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Wrong time when adding two dates

807588Mar 24 2009 — edited Mar 25 2009
Hi

I'm trying to add two Date-objects by adding milliseconds they represent, and convert back to a Date-object. More specific, I have a Date representing midnight on a given day, and another Date representing a time offset on this day, and I want to get a Date representing the time and date on one.

I have made the following example code:
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();

        c1.set(2009, Calendar.MARCH, 24, 0, 0, 0);
        c1.set(Calendar.MILLISECOND, 0);

        c2.set(1970, 0, 1, 11, 38, 0);
        c2.set(Calendar.MILLISECOND, 0);

        long m1 = c1.getTimeInMillis();
        long m2 = c2.getTimeInMillis();

        Date test = new Date(m1);
        Date test2 = new Date(m2);
        Date test3 = new Date(m1 + m2);
        System.out.println(test);
        System.out.println(test2);
        System.out.println(test3);
Which outputs
Tue Mar 24 00:00:00 CET 2009
Thu Jan 01 11:38:00 CET 1970
Tue Mar 24 10:38:00 CET 2009
The result is an hour wrong!? What am I doing wrong? I suspect it's a timezone issue of some kind, but I don't understand why timezone is an issue in this case?

Ulrik
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 22 2009
Added on Mar 24 2009
29 comments
426 views