La conversión de Java Fecha de OffsetDateTime

user6728767:

Tengo un valor de eta que es un OffsetDateTime y tengo una scheduledDate que es un tipo de fecha. Si la ETA no se establece Quiero caer de nuevo a la fecha.

Un ejemplo de la fecha es Tue Jul 21 10:32:28 PDT 2020. Para convertir esto, he intentado hacer: OffsetDateTime.ofInstant(dto.getScheduledTime().ToInstant(), ZoneOffset.UTC) Se siente como el desplazamiento UTC es incorrecto ya que la fecha tiene la TFD en ella ya, pero, al mismo tiempo que también no es un TimeZoneID como "América / Los_Angeles".

Estoy un poco confundido sobre cómo manejar esto.

Albahaca Bourque:

tl; dr

OffsetDateTime target, eta;    // Modern java.time class.
java.util.Date scheduledDate;  // Terrible legacy class.


if(Objects.isNull(eta)) {   // If no eta, fall back to scheduledDate.
    target = scheduledDate.toInstant().atOffset( ZoneOffset.UTC ); // Never use legacy class `java.util.Date` -- when encountered, immediately convert to modern `java.time.Instant`. 
} else {  // Else not null.
    target = eta;
}
return target;

Es mejor evitar por completo java.util.Date. Cuando encontrado, convertir inmediatamente a la clase moderna Instant, y olvidar todo sobre el Dateobjeto.

OffsetDateTime target, eta, scheduled;
scheduled = incomingJavaUtilDate.toInstant().atOffset(ZoneOffset.UTC);

target = Objects.isNull(eta) ? scheduledDate : eta;  // Ternary operator. Short way of saying: If eta is null, go with scheduledDate, otherwise go with eta. 
return target;

Date::toString te miente

En primer lugar, entender que java.util.Daterepresenta un momento en UTC, siempre en UTC . Sin embargo, su toStringmétodo tiene la bien intencionada por terriblemente confuso anti-función de la aplicación de forma dinámica zona horaria predeterminada actual de la JVM. Esto crea la falsa impresión de que Datetiene una zona horaria cuando de hecho no lo hace .

Evitar el legado clases de fecha y hora

En segundo lugar, usted está mezclando innecesaria y trágicamente los muy buenos modernos java.time clases ( OffsetDateTime) con las clases legado de fecha y hora terriblemente horrible ( Date). No hagas esto. Evitar las clases heredadas por completo. Estaban obsoletos por la adopción de JSR 310 de nuevo en 2014.

tabla de clases de fecha y hora en Java, tanto heredados como moderna

uso java.time

If handed a java.util.Date object, immediately convert to java.time. Call the new conversion methods added to the old classes. The Instant class directly replaces Date, as a moment in UTC, but with finer resolution of nanoseconds versus milliseconds.

Instant instant = myJavaUtilDate.toInstant();  // Convert from legacy class to modern class.

You should generally be tracking moments in UTC. You can do this as an Instant or as a OffsetDateTime with its offset set to ZoneOffset.UTC constant.

OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);  // Same moment, no change in meaning whatsoever. 

For UTC specifically, there is no difference between the instant and the odt in our code here. They both represent a moment in UTC. The difference is that OffsetDateTime (a) could carry an alternate offset-from-UTC value (hours-minutes-seconds), and (b) is more flexible, such as generating text in formats other than standard ISO 8601.

Understand that an offset-from-UTC is merely a number of hours, minutes, and seconds. Nothing more. A time zone, in contrast, is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a particular region. For example, the people in region using America/Los_Angeles time zone change their offset-from-UTC twice a year in a silly practice known as Daylight Saving Time (DST) going from -08:00 to -07:00 and back again.

So generally a time zone is preferable over a mere offset. For example, to see your Date we turned into a Instant through the wall-clock time used by most people on the west coast of US, apply the time zone America/Los_Angeles (ZoneId) to the Instant to get a ZonedDateTime.

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

Puede volver a UTC mediante la extracción de una Instant.

Instant instant = zdt.toInstant();

Y desde allí volver a una java.util.Date(si es necesario, de lo contrario evitar).

java.util.Date d = java.util.Date.from(instant);

En realidad, la java.time.Dateclase hace tener una zona horaria enterrado en el interior profundo. Al carecer de descriptor de acceso (get / set) métodos, es inalcanzable. Sus comportamientos no se relacionan con nuestra discusión aquí. ¿Confuso? Si. Sin embargo, otra de las muchas razones para evitar las clases heredadas de fecha y hora terribles.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=137047&siteId=1
Recomendado
Clasificación