tl;dr
In extreme data loads where you want to minimize object creation, keep your DateTimeFormatter
object(s) around for re-use. That class is inherently thread-safe, so you may re-use across threads.
java.time
Some years ago, the troublesome date-time classes such as Date
and Calendar
and SimpleDateFormat
were supplanted entirely by the modern java.time classes defined in JSR 310.
One of the many benefits to the java.time classes: They are thread-safe by design, using immutable objects. So you can keep them around for re-use.
LocalDate
For a date-only value, without time-of-day and without time zone, use the LocalDate
class.
LocalDate ld = LocalDate.of( 2019 , 1 , 23 ) ;
To generate text in standard ISO 8601 format of YYYY-DD-MM, simply call toString
.
String output = ld.toString() ; // ISO 8601 format.
DateTimeFormatter
For other formats, use the DateTimeFormatter
class.
Again, you can safely keep objects of this class around for re-use across threads. Loop through multiple DateTimeFormatter
objects, trying each in succession, trapping for DateTimeParseException
until one succeeds.
If concerned about efficiency and minimizing object creation because of extreme data loads, be clever about identifying which formatter(s) may be appropriate to a particular input. For example, the length of the string may tell you which formatter to use.
Also, be aware that with the DateTimeFormatterBuilder
class, you can specify optional parts. This effectively lets a single formatter parse multiple kinds of inputs.
Let the JVM work for you
Lastly, a caution: Worrying about creating too many objects is almost certainly unwarranted.
The modern JVMs are extremely well-tuned and effective. They commonly have special handling for short-lived objects for efficient disposal. Do not fall into the trap of premature-optimization: Use profiling to prove you have a measurable performance problem before writing squirrelly code.