Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create only one static instance of DateTimeFormatter

Is it possible to create only one static instance of DateTimeFormatter and use it everywhere in my project, instead of creating it multiple times?

public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

Can there be thread-safety issues in such cases?

like image 205
munish Avatar asked Jan 31 '18 11:01

munish


People also ask

What is the role of the DateTimeFormatter type in Java?

Class DateTimeFormatter. Formatter for printing and parsing date-time objects. This class provides the main application entry point for printing and parsing and provides common implementations of DateTimeFormatter : Using predefined constants, such as ISO_LOCAL_DATE.

Is DateTimeFormatter thread safe?

DateTimeFormatter is immutable and thread-safe. DateTimeFormatter formats a date-time using user defined format such as "yyyy-MMM-dd hh:mm:ss" or using predefined constants such as ISO_LOCAL_DATE_TIME. A DateTimeFormatter can be created with desired Locale, Chronology, ZoneId, and DecimalStyle.

What is the Java time format DateTimeFormatter?

format. DateTimeFormatterBuilder Class in Java. DateTimeFormatterBuilder Class is a builder class that is used to create date-time formatters. DateTimeFormatter is used as a Formatter for printing and parsing date-time objects.

How do I use DateTimeFormatter with date?

DateTimeFormatter fmt = DateTimeFormatter. ofPattern("yyyy-MM-dd'T'HH:mm:ss"); System. out. println(ldt.


1 Answers

Yes, it is possible. Your variable is Thread Safe because it is immutable - No other thread can change it. Other solutions are also possible in your specific case, but I am always in favour of immutable objects.

See Java Concurrency in practice Chapter 3. By the way, the chapter seems to be free to browse now, so have a look.

like image 183
user1156544 Avatar answered Oct 14 '22 12:10

user1156544