Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeFormatter to DateFormat conversion

Tags:

java

date

How to convert a DateTimeFormatter to DateFormat ? I want to cast DateTimeFormatter to DateFormat ? Is it possible ?

I have a object of DateTimeFormatter and I want to pass it to a method whose parameter only accepts DateFormat.

like image 510
user6374672 Avatar asked May 24 '16 13:05

user6374672


People also ask

What is the difference between DateTimeFormatter and SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

What is the Java time format DateTimeFormatter?

DateTimeFormatter is used as a Formatter for printing and parsing date-time objects. DateTimeFormatterBuilder allows a DateTimeFormatter to be created. It is used for constructing formatters which are then used to print or parse.

What is DateTimeFormatter Iso_date_time?

static DateTimeFormatter. ISO_DATE_TIME. The ISO-like date-time formatter that formats or parses a date-time with the offset and zone if available, such as '2011-12-03T10:15:30', '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.


1 Answers

There is no backward conversion from java.time.format.DateTimeFormatter to the old formatter class.

The newer java.time classes are intended to supplant the old ones. They are not intended to be mixed or interoperate. The old date-time classes have proven to be poorly designed, confusing, and troublesome.

Go forward, not backward

The old date-time classes bundled with the earliest versions of Java are now legacy. Classes such as java.util.Date/.Calendar and java.text.DateFormat/.SimpleDateFormat should be avoided.

Those old classes have been supplanted by the java.time framework built into Java 8 and later. Much of that functionality is back-ported to Java 6 & 7 in the ThreeTen-Backport project, and further adapted to Android in the ThreeTenABP project.

Instead, go forward. Convert your old date-time objects to the modern java.time classes. New methods have been added to the old classes to facilitate conversion of your data.

If you have a java.util.Date, call toInstant(). If you have a java.util.Calendar object, convert to a ZonedDateTime.

To get started, see my Question and my Answer with nifty diagram of types.

like image 65
Basil Bourque Avatar answered Sep 20 '22 06:09

Basil Bourque