M Sach
M Sach

Reputation: 34424

Does java Date handles localization(one of the reason to choose Calendar over Date)?

I always preferto use calendar over date class as its robust on date manipulation(Also i read somewhere Date class mainly exist becoz of backward compatibility probably for prior to jdk 1.1).But i think today i have got one more reason to go with calendar i.e calendar handles the localization which means that when i do

Calendar.getInstance()

it will return the calendar object depending on timezone and locale of box where code is deployed. But when i do

new Date()

it will return the date object in respect to GMT(thats the feeling i got after going thru http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Date.html#Date())

Is that correct?

Upvotes: 1

Views: 177

Answers (2)

dratewka
dratewka

Reputation: 2114

A Date object internally stores the date as a number of miliseconds since January 1, 1970 UTC. However when you are accessing for example the hour represented by a Date object it DOES consider timezone information. This can be verified using this simple code:

import java.util.Date;
public class Main {

    public static void main(String[] args) {
        Date date = new Date(1368868487441L);

        System.out.println(date);
    }
}

Now if you run it setting the timezone (as a JVM startup parameter) to -Duser.timezone="Europe/Sofia" you get

Sat May 18 12:14:47 EEST 2013

but if you change it to -Duser.timezone="America/Arizona" the result is different

Sat May 18 09:14:47 GMT 2013

This is because Date actually uses a Calendar instance internally to convert from the number of milis since "the Epoch" to the actual time values.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691755

A Date represents an instant in time, and doesn't care about the time zone and locale. You only care about time zone and locale when you want to parse or format a date for a human (using SimpleDateFormat), or when you start comparing the date with some wall-clock value, wondering if the date is within a given month, day or hour, or adding days and taking daylight savings into account (and in this case you transform the date into a Calendar).

So Date isn't inherently a less useful class than Calendar. It just doesn't serve the same purpose. Both are complementary.

I would recommend using joda-time anyway, which is a much better API, but still has the same concepts of an instant, and of a zoned date time.

Upvotes: 4

Related Questions