Difference between Date, sql.Date and Calendar

30

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

    
asked by rray 10.04.2014 в 15:21
source

3 answers

26

It's 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 speak in "before" or "after" with this class, or use it as a "timestamp" to know when something happened.

The java.sql.Date class is also there from the beginning, and note that it extends java.util.Date . It basically serves to get JDBC (relational database access) to convert between java.util.Date and DATE of SQL. Do not worry about this class - if you need it, you'll know.

Before going to Calendar , we'll see some problems with Date . First, you can get day, month, year, hour, minute, and second, but has no time zone information . That is, if you have Date , you can not tell if it is relative to Brasilia or New York time (which will be daylight saving time). Or, more precisely, it always refers to the GMT time.

In addition, this class does not allow you to do "two-day" or "two-hour" accounts - you have to implement the logic for it yourself. In some respects it is even easy: add as many seconds as you need. But if you need to deal with things like summer time, it's simply 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 java.util.Calendar class and some others (particularly java.text.SimpleDateFormat ) were introduced in Java 1.1, donated by IBM from the code of one of its affiliates (the Taligent) to solve those problems. It introduces time zones, daylight saving time, and location (ie convert from / to strings in the appropriate format for the language and region).

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

So which one to use? DO NOT USE ANY OF THESE CLASSES . They are full of defects - I would need a whole answer just to discuss it - and there are much better alternatives.

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

    
answered by 10.04.2014 / 21:23
source
18

java.util.Date - Date (Java SE7)

It's a class representing date.

It has some overloaded builder versions, its non-obsolete builders 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;
}

Soon, the following code

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

Outputs the following output:

Thu Apr 10 10:36:15 BRT 2014

java.sql.Date - Date (Java SE7)

It is 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 a Sql Statement.

java.util.Calendar - Calendar (Java SE7)

It is an abstract class that has useful methods of converting and comparing date, 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 behaviors of the java.util.Date and java.util.Calendar classes are considered strange for most Java programmers, so the library JodaTime is preferred when scheduling involves date and time.

Joda-Time has 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 example above shows only some of the many methods that the class has, it has more methods than the classes that the class overrides and they are all very intuitive.

    
answered by 10.04.2014 в 16:04
9

java.util.Date is a simple class and only exists for reasons of backward compatibility. It really is not very useful, because it only saves dates, without manipulation operations.

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

Both are changeable.

java.sql.Date extends java.util.Date . It has some more properties for working with databases.

    
answered by 10.04.2014 в 16:02