Difference between Date, sql. Date and Calendar

Asked

Viewed 4,357 times

31

What is the difference between the classes java.util.Date, java.sql.Date and java.util.Calendar and in which situations the use of one or the other is recommended?

  • 3

    The recommended is to use the Jodatime :)

  • 1

    Recommended is to use JSR-310. It comes with Java 8, and can be downloaded for Java 7.

3 answers

30


It is best to understand this from a historical point of view.

The first version of Java had a class for date and time: java.util.Date. This class contains information: an instant in time. It makes sense to mention "before" or "after" with this class, or use it as a "timestamp" to know when something happened.

The class java.sql.Date is also there from the beginning, and note that she extends java.util.Date. It basically serves to pass that the JDBC (relational database access) can convert between java.util.Date and the DATE SQL. Don’t worry about this class -- if you need it, you’ll know.

Before going to Calendar, let’s see some problems with Date. First, you can get day, month, year, hour, minute and second, but no information about time zone. That is, if you have one Date, It is not known if it is related to Brasilia or New York time (which will say daylight saving time). Or more precisely, it always refers to GMT time.

Also, this class does not allow you to do "two days' time" or "two hours' time" - you have to implement the logic for that yourself. In certain aspects it is even easy: add up the amount of seconds needed. But if you have to deal with things like daylight savings, it’s just impossible.

Finally, this class only allows a representation of String: the American. If you need to read or write in any other format, you are on your own.

The class java.util.Calendar and some others (particularly java.text.SimpleDateFormat) were introduced in Java 1.1, donated by IBM from the code of one of its affiliates (Taligent), to solve these problems. It introduces time Zones, daylight saving time, and location (i.e., converting from/to strings with the format suitable for language and region).

Basically, Calendar would be used for anything other than knowing at what instant an event took place.

So which to use? DO NOT USE ANY OF THESE CLASSES. They are full of flaws -- I would need an entire answer just to talk about it -- and there are much superior alternatives.

You should preferably use the new classes in the package java.time.*, introduced with Java 8. If you don’t have Java 8 but have Java 7, use the backport of these classes, the threetenbp. If you don’t even have that, use the JODA Time, which was created precisely because of the problems with the original Java classes, and which was the starting point for the new Java 8 classes.

  • Excellent explanation. Thank you.

  • One of the answers I most use as a reference in mine here at SOPT :)

19

java.util.Date - Date (Java SE7)

It is a class representing date.

It has some overloaded constructor versions, its not obsolete constructors are:

public Date() {
    this(System.currentTimeMillis()); //o construtor vazio já atualiza a variável com a data
                                      //e hora atuais
}
public Date(long date) {
    fastTime = date; //sua declaração é: private transient long fastTime;
}

Therefore, the following code

java.util.Date d = new java.util.Date();
System.out.println(d);

Outputs the following result:

Thu Apr 10 10:36:15 BRT 2014

java.sql.Date - Date (Java SE7)

It’s a subclass of java.util.Date.

It has two constructors, one of them is obsolete, so it is recommended to use the following:

public Date(long date) {
    // If the millisecond date value contains time info, mask it out.
    super(date); //chama o construtor do java.util.Date
}

Its main advantage is that a reference variable of this class can be used directly in an Sql Statement.

java.util.Calendar - Calendar (Java SE7)

It is an abstract class that has useful conversion and date comparison methods, for example:

public static Calendar DateToCalendar(java.util.Date date){ 
  java.util.Calendar cal = java.util.Calendar.getInstance(); //instancia um BuddhistCalendar
                                         //ou um GregorianCalendar dependendo das
                                         //configuracoes do seu computador

  cal.setTime(date); //seta a data do java.util.Date para sua variável de referencia
                     //considere que a data passada foi o do primeiro exemplo,
                     //ou seja: Thu Apr 10 10:36:15 BRT 2014
  System.out.println(cal.after(new java.util.Date())); //retorna false, pois hoje não
                                                       //é depois de hoje
  cal.add(java.util.Calendar.HOUR_OF_DAY, -1); //subtrai um da hora do cal
  System.out.println(cal.get(java.util.Calendar.HOUR_OF_DAY)); //retorna 9, que é a hora
                                                               //do cal (que foi subtraida 
                                                               //logo acima)
}

Some examples of useful methods are:

add(int field, int amount) //para somar um período de tempo à data da váriavel
after(Object when)         //para comparar se data atual é depois da data do when
before(Object when)        //para comparar se data atual é antes da data do when

among others.

Joda-Time

Many of the class behaviors java.util.Date and java.util.Calendar are considered strange to most Java programmers, so the library Jodatime is preferred when the schedule involves date and time.

Joda-Time owns the class Datetime, which has the ability to completely replace both classes. Example:

org.joda.time.DateTime joda1 = new org.joda.time.DateTime();//inicializa com data/hora atuais
System.out.println(joda1); //imprime 2014-04-10T11:35:09.000-03:00

//cria um novo objeto com 5 horas a menos que o joda1
org.joda.time.DateTime joda2 = new org.joda.time.DateTime(joda1.minusHours(5)); 
System.out.println(joda1.isAfter(joda2)); //retorna true

The above example shows just a few of the numerous methods that the class has, it has more methods than the classes that the class replaces and they all tend to be very intuitive.

  • A much discussed disadvantage of Joda-Time is that information about time Zones and daylight hours change frequently and if you do not manually update the library it may generate incorrect values. Of course the same happens if the person uses Calendar in an old JRE. Well, that was something I read some time ago. Personally I never had trouble using the Calendar.

  • @utluiz About Calendar, I can’t remember in my head what he leaves to be desired, but I know I’ve had setbacks, already joda always found simple and versatile. About the discussion, I had never heard about, maybe because I never needed much precision in calculating the hours, in my cases making mistakes for an hour or two was never a problem, usually what is used is the date, but it is always good to know these peculiarities.

  • 1

    The biggest problem in the class Calendar, from my point of view, is its mutability. We can not change the content of Strings and primitive Wrappers, but the same is not true for the Calendar. This can lead to serious problems if some method inadvertently modifies the instance we have passed.

9

java.util.Date is a simple class and only exists for compatibility reasons with previous versions. Actually it is not very useful, because it only keeps dates, without the manipulation operations.

java.util.Calendar came after and fulfills this function, to set specific dates or do date arithmetic, java.util.Calendar can also handle the location. The date manipulation functions of the java.util.Date have already been discontinued.

Both are mutable.

java.sql.Date extend java.util.Date. Has a few more properties to work with databases.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.