-3

I looking for a function which will format date into given format if type of date or any other implementation else throw exception

Eg: formatDate(java.util.Date date) Or formatDate(org.joda.time.LocalDateTime) or formatDate(any valid date implementation) eg: java.time.LocalDateTime , javax.xml.datatype.XMLGregorianCalendar or other date time implementation

I cannot be sure for the type of date i receive so don't ask me to implement same date type everywhere in project

Piyush Sonavale
  • 13
  • 1
  • 1
  • 5
  • Did you look at [SimpleDateFormat](https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) or [DateTimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) ? – Arnaud Denoyelle Jul 25 '19 at 14:02
  • Use Java method overloading? – Mark B Jul 25 '19 at 14:03
  • When you receive a `Date` or `XMLGregorianCalendar`, just convert them to a `LocalDateTime`. Then you can base all your other code on that class, regardless of how you initially receive it. – TiiJ7 Jul 25 '19 at 14:12

2 Answers2

0

LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); for example will format into a string such as: 2019-07-25T15:05:54.432

Other formats are available, practically every standard format you could want is included as a static constant in the class. However, it also supports custom patterns, the following page explains how to create these: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

cameron1024
  • 9,083
  • 2
  • 16
  • 36
0

Two options that I would at least consider:

  1. One method that takes an Object argument. Inside the method do a long chain of if-else using instanceof to find the right type. If you want to support the java.sql types that extend java.util.Date (an awful hack), remember to test for those first because instanceof java.util.Date will also be true. Down side: Your user will not get a compile-time error for passing an unsupported type and may find it difficult to find out why your method throws an exception given a String or an Integer, for example (which may represent dates too).
  2. An overloaded method for each supported type, as @MarkB suggested in a comment. Down side: You need to modify your API for each new supported type added.

Whether you choose one option or the other, convert whatever you get to something that implements TemporalAccessor and pass it to DateTimeFormatter.format().

Just mentioned as a curiosity, String.format() already implements some of the functionality you envision. It handles TemporalAccessor, Calendar, Date and Long.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161