Pregunta

¿Alguien podría informarle sobre la " mejor práctica actual " alrededor de los tipos Fecha y Calendario .

Al escribir un código nuevo, es mejor favorecer siempre Calendar sobre Date , o hay circunstancias en las que Date es el tipo de datos más apropiado ?

¿Fue útil?

Solución

La fecha es una clase más simple y está principalmente allí por razones de compatibilidad con versiones anteriores. Si necesita establecer fechas particulares o hacer aritmética de fechas, use un Calendario. Los calendarios también manejan la localización. Las funciones de manipulación de fechas anteriores de Date ya han quedado en desuso.

Personalmente, tiendo a usar el tiempo en milisegundos como largo (o Largo, según corresponda) o Calendario cuando hay una opción.

Tanto la fecha como el calendario son mutables, lo que tiende a presentar problemas al usar cualquiera de los dos API.

Otros consejos

La mejor manera de obtener un nuevo código (si su política permite el código de terceros) es utilizar la biblioteca de Joda Time .

Ambos, Fecha y Calendario , tienen tantos problemas de diseño que tampoco son buenas soluciones para nuevo código.

  • Date y Calendar son realmente el mismo concepto fundamental (ambos representan un instante en el tiempo y son envoltorios alrededor de un subyacente < code> long value).

  • Se podría argumentar que Calendar está incluso más roto que Date , ya que parece ofrecer datos concretos sobre las cosas como el día de la semana y la hora del día, mientras que si cambia su propiedad timeZone , el concreto se convierte en blanco. Ninguno de los objetos es realmente útil como almacén de año-mes-día o hora del día por este motivo.

  • Use Calendar solo como una calculadora que, cuando se le den los objetos Date y TimeZone , hará los cálculos por usted. Evite su uso para escribir propiedades en una aplicación.

  • Use SimpleDateFormat junto con TimeZone y Date para generar cadenas de visualización.

  • Si se siente aventurero, use Joda-Time, aunque en mi humilde opinión es innecesariamente complicado y pronto será reemplazado por la API de fecha JSR-310 en cualquier caso.

  • He respondido anteriormente que no es difícil rodar su propia clase YearMonthDay , que utiliza Calendar bajo el capó para realizar cálculos de fecha. Me rechazaron la sugerencia, pero sigo creyendo que es válida porque Joda-Time ( y JSR-310 ) son realmente demasiado complicados para la mayoría de los casos de uso.

La fecha es la mejor para almacenar un objeto de fecha. Es el persistente, el serializado ...

El calendario es mejor para manipular fechas.

  

Nota: a veces también favorecemos java.lang. Long over Date, porque Date es mutable y, por lo tanto, no es seguro para subprocesos. En un objeto Date, use setTime () y getTime () para cambiar entre los dos. Por ejemplo, una fecha constante en la aplicación (ejemplos: el cero 01/01/1970 o un END_OF_TIME aplicativo que establezca en 2099/12/31; estos son muy útiles para reemplazar los valores nulos como hora de inicio y hora de finalización, especialmente cuando los persiste en la base de datos, ya que SQL es tan peculiar con los nulos).

Generalmente uso Fecha si es posible. Aunque es mutable, los mutadores están en desuso. Al final, básicamente envuelve un largo que representaría la fecha / hora. Por el contrario, usaría Calendarios si tuviera que manipular los valores.

Puedes pensarlo de esta manera: solo usas StringBuffer solo cuando necesitas tener Strings que puedes manipular fácilmente y luego convertirlos en Strings usando el método toString (). Del mismo modo, solo uso el Calendario si necesito manipular datos temporales.

Para las mejores prácticas, tiendo a usar objetos inmutables tanto como sea posible fuera del modelo de dominio . Reduce significativamente las posibilidades de cualquier efecto secundario y lo realiza el compilador en lugar de una prueba de JUnit. Utiliza esta técnica al crear campos finales privados en tu clase.

Y volviendo a la analogía de StringBuffer. Aquí hay un código que le muestra cómo convertir entre el calendario y la fecha

String s = "someString"; // immutable string
StringBuffer buf = new StringBuffer(s); // mutable "string" via StringBuffer
buf.append("x");
assertEquals("someStringx", buf.toString()); // convert to immutable String

// immutable date with hard coded format.  If you are hard
// coding the format, best practice is to hard code the locale
// of the format string, otherwise people in some parts of Europe
// are going to be mad at you.
Date date =     new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2001-01-02");

// Convert Date to a Calendar
Calendar cal = Calendar.getInstance();
cal.setTime(date);

// mutate the value
cal.add(Calendar.YEAR, 1);

// convert back to Date
Date newDate = cal.getTime();

// 
assertEquals(new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2002-01-02"), newDate);
Las

Date s deben usarse como puntos inmutables en el tiempo; Los Calendar s son mutables, y se pueden pasar y modificar si necesita colaborar con otras clases para llegar a una fecha final. Considérelos análogos a String y StringBuilder y comprenderá cómo considero que deberían usarse.

(Y sí, sé que Date no es en realidad técnicamente inmutable, pero la intención es que no sea mutable, y si nada llama a los métodos obsoletos, entonces es así).

tl;dr

advise the current "best practice" around Date and Calendar

is it best to always favour Calendar over Date

Avoid these legacy classes entirely. Use java.time classes instead.

  • For a moment in UTC, use Instant
    (the modern equivalent of Date)
  • For a moment in a particular time zone, use ZonedDateTime
    (the modern equivalent of GregorianCalendar)
  • For a moment in a particular offset-from-UTC, use OffsetDateTime
    (no equivalent in legacy classes)
  • For a date-time (not a moment) with unknown time zone or offset, use LocalDateTime
    (no equivalent in legacy classes)

Details

The Answer by Ortomala Lokni is right to suggest using the modern java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.). But that Answer suggests the wrong class as equivalent (see my comment on that Answer).

Using java.time

The java.time classes are a vast improvement over the legacy date-time classes, night-and-day difference. The old classes are poorly-designed, confusing, and troublesome. You should avoid the old classes whenever possible. But when you need to convert to/from the old/new, you can do so by calling new methods add to the old classes.

For much more information on conversion, see my Answer and nifty diagram to another Question, Convert java.util.Date to what “java.time” type?.

Searching Stack Overflow gives many hundreds of example Questions and Answers on using java.time. But here is a quick synopsis.

Instant

Get the current moment with an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now();

ZonedDateTime

To see that same simultaneous moment through the lens of some particular region’s wall-clock time, apply a time zone (ZoneId) to get a ZonedDateTime.

Time zone

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone();

Offset

A time zone is a region’s history of changes in its offset-from-UTC. But sometimes you are given only an offset without the full zone. In that case, use the OffsetDateTime class.

ZoneOffset offset = ZoneOffset.parse( "+05:30" );
OffsetDateTime odt = instant.atOffset( offset );

Use of a time zone is preferable over use of a mere offset.

LocalDateTime

The “Local” in the Local… classes means any locality, not a particular locality. So the name can be counter-intuitive.

LocalDateTime, LocalDate, and LocalTime purposely lack any information about offset or time zone. So they do not represent actual moments, they are not points on the timeline. When in doubt or in confusion, use ZonedDateTime rather than LocalDateTime. Search Stack Overflow for much more discussion.

Strings

Do not conflate date-time objects with strings that represent their value. You can parse a string to get a date-time object, and you can generate a string from a date-time object. But the string is never the date-time itself.

Learn about standard ISO 8601 formats, used by default in the java.time classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

With Java 8, the new java.time package should be used.

Objects are immutable, time zones and day light saving are taken into account.

You can create a ZonedDateTime object from an old java.util.Date object like this:

    Date date = new Date();
    ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault());

I always advocate Joda-time. Here's why.

  1. the API is consistent and intuitive. Unlike the java.util.Date/Calendar APIs
  2. it doesn't suffer from threading issues, unlike java.text.SimpleDateFormat etc. (I've seen numerous client issues relating to not realising that the standard date/time formatting is not thread-safe)
  3. it's the basis of the new Java date/time APIs (JSR310, scheduled for Java 8. So you'll be using APIs that will become core Java APIs.

EDIT: The Java date/time classes introduced with Java 8 are now the preferred solution, if you can migrate to Java 8

A little bit late at party, but Java has a new Date Time API in JDK 8. You may want to upgrade your JDK version and embrace the standard. No more messy date/calendar, no more 3rd party jars.

Date should be re-developed. Instead of being a long interger, it should hold year, month, date, hour, minute, second, as separate fields. It might be even good to store the calendar and time zone this date is associated with.

In our natural conversation, if setup an appointment at Nov. 1, 2013 1pm NY Time, this is a DateTime. It is NOT a Calendar. So we should be able to converse like this in Java as well.

When Date is stored as a long integer (of mili seconds since Jan 1 1970 or something), calculating its current date depends on the calendar. Different calendars will give different date. This is from the prospective of giving an absolute time (eg 1 trillion seconds after Big Bang). But often we also need a convenient way of conversation, like an object encapsulating year, month etc.

I wonder if there are new advances in Java to reconcile these 2 objectives. Maybe my java knowledge is too old.

Btw "date" is usually tagged as "obsolete / deprecated" (I dont know exactly why) - something about it is wrote there Java: Why is the Date constructor deprecated, and what do I use instead?

It looks like it's a problem of the constructor only- way via new Date(int year, int month, int day), recommended way is via Calendar and set params separately .. (Calendar cal = Calendar.getInstance(); )

I use Calendar when I need some specific operations over the dates like moving in time, but Date I find it helpful when you need to format the date to adapt your needs, recently I discovered that Locale has a lot of useful operations and methods.So I'm using Locale right now!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top