7

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.

user6374672
  • 105
  • 2
  • 8
  • For what method your need DateFormat? Maybe your should find out appropriate method whose parameter is DateTimeFormatter? – Oleg Baranenko May 24 '16 at 13:30
  • 1
    you can convert a DateTimeFormatter to a java.text.Format with : java.text.Format oldformat = dateTimeFormatter.toFormat(); – Ben May 24 '16 at 13:44
  • @ben Can you provide a link to class doc? I see no such method on either DateFormat or SimpleDateFormat. – Basil Bourque May 24 '16 at 17:36
  • 1
    See here : https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html : "Some applications may need to use the older java.text.Format class for formatting. The toFormat() method returns an implementation of java.text.Format." – Ben May 25 '16 at 09:36

1 Answers1

3

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 16
    Yes, but what to do when you are using an API (jackson-databind) using `DateFormat` such as in this question : http://stackoverflow.com/questions/39955104/using-datetimeformatter-with-objectmapper – Ortomala Lokni Oct 10 '16 at 09:35