tl;dr
format.parse( Info.get("TIME") ) // Get a legacy `java.util.Date` object.
.toInstant() // Convert from legacy class to modern class.
.atOffset( // Convert from the basic `Instant` class to the more flexible `OffsetDateTime` class.
ZoneOffset.UTC // Specify the offset-from-UTC in which you want to view the date and time-of-day.
)
.format( // Generate text representing the value of our `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "dd/MM/yyyy HH:mm:ss" ) // Specify your custom formatting pattern. Better to cache this object, in real work.
) // Returns a `String
Date
was replaced years ago by Instant
. The Instant::toString
method uses a much better format, a modern standard format.
Instant.now().toString()
2019-06-04T20:11:18.607231Z
Convert your Date
objects, myDate.toInstant()
.
Details
The Object::toString
method is not meant to be flexible. Its purpose is to to provide a simplistic view of an object while debuggig or logging.
However, as you have seen, the java.util.Date::toString
implementation is terrible.
First it lies, applying the JVM’s current default time zone to the moment stored in the Date
object. That moment is actually in UTC. This misreporting creates the illusion of a time zone that is not actually in the object.
Secondly, the Date::toString
method uses a terrible format, English only, difficult to read by humans, and difficult to parse by machine.
The Date
class has many other problems. You should no longer use this class at all. With the adoption of JSR 310, it was supplanted by the java.time.Instant
class.
You should replace Date
with Instant
wherever you can. Where you cannot, convert. Call new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Fortunately, the toString
method on Instant
is much better designed. It tells you the truth, a moment in UTC. And it uses the standard ISO 8601 formats. That standard was invented expressly for communicating date-time values as text in a way that is both easy to parse by machine and easy to read by humans across cultures.
String output = instant.toString() ;
2019-06-04T20:11:18.607231Z
So a list of Instant
objects will look like this.
Instant now = Instant.now();
List < Instant > instants = List.of( now.minus( 1L , ChronoUnit.HOURS ) , now , now.plus( 20L , ChronoUnit.MINUTES ) );
String output = instants.toString();
[2019-06-04T19:41:51.210465Z, 2019-06-04T20:41:51.210465Z, 2019-06-04T21:01:51.210465Z]
Your code snippet
As for your code snippet, convert to a java.time.OffsetDateTime
object, and generate text using a custom-defined formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/yyyy HH:mm:ss" ) ;
…
if(Info.get("TIME")!=null)
{
try {
Date date = format.parse( Info.get("TIME") ) ;
Instant instant = date.toInstant() ;
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
String output = odt.format( f ) ;
message.TimeHistory.add(date);
}
catch (Exception e){
}
}