Avoid obsolete time classes
The java.time classes have been replaced by the difficult old time classes associated with the earliest versions of Java. The java.time classes are thread safe and use immutable objects .
java.time
Replace formatting types and dates with java.time types to automatically ensure thread safety.
If you want, define your DateTimeFormatter globally. This class can automatically localize the generated string or specify a specific format.
- Specify
FormatStyle to determine the length of the abbreviation. - Indicate
Locale to define (a) human language for translating the name of the day, the name of the month, etc. And (b) cultural norms that address issues of contraction, capitalization, punctuation, etc. - Specify the
ZoneId for the time zone where you can configure the moment.
The Instant class represents a moment in the UTC timeline with a nanosecond resolution. The ZonedDateTime class sets Instant to a specific time zone.
Your code translated into java.time classes. In real work, I would break it into several lines and catch for exceptions.
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ; private static final ZoneId ZONE_ID = ZoneId.of( "America/Montreal" ); public static final String eventTypeToDateTimeString(long timestamp) { return Instant.ofEpochMilli( timestamp ).atZone( ZONE_ID ).format( DATE_TIME_FORMATTER ); }
Do not track date-time as a countdown from an era
I do not recommend laying a long path for representing date and time values. It makes debugging and registration difficult, since a person cannot distinguish between the meaning of date and time. Instead, switch to java.time types such as Instant . Using java.time types ensures type safety and makes your code more self-documenting.
About java.time
The java.time framework is built into Java 8 and later. These classes supersede the nasty old obsolete time classes such as java.util.Date , Calendar and SimpleDateFormat .
The Joda-Time project, now in maintenance mode , advises switching to the java.time classes.
To learn more, check out the Oracle tutorial . And search for qaru for many examples and explanations. The specification is JSR 310 .
You can exchange java.time objects directly with your database. Use a JDBC driver compatible with JDBC 4.2 or later. No strings needed, no java.sql.* Needed.
Where can I get java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and others .