Below code converts a date format from "yyyy-MM-dd'T'HH:mm:ss"
to "MM/dd/yyyy"
.
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class TestDate {
public static void main(String[] args) {
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
DateTime dateTime = parser.parseDateTime("2014-05-19T23:59:59");
DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy");
System.out.println(formatter.print(dateTime)+"\n");
dateTime = parser.parseDateTime("2014-06-09T03:00:23.67");
formatter = DateTimeFormat.forPattern("MM/dd/yyyy");
System.out.println(formatter.print(dateTime));
}
An exception is thrown for "2014-06-09T03:00:23.67"
:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2014-06-09T03:00:23.67" is malformed at ".67"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:899)
at TestDate.main(TestDate.java:16)
I need to be able to cater for other possibilities also such as :
2014-05-27T03:00:32.613
I just require the "MM/dd/yyyy"
part of the date, everything subsequent to that can be ignored. Do I need to anticipate every date format explained at Using Joda Date & Time API to parse multiple formats
Or can a wildcard be used which ignores everything after a certain pattern. Something like :
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd%");
Or I could parse the string and split at the 'T' section of the date time, just using the value that appears before 'T', though this seems unclean....
Or is there an alternative method ?
Update :
Since time is not required, instead of using :
String strDate = "2014-05-19T23:59:59";
DateTime dateTime = parser.parseDateTime(strDate);
will use :
String strDate = "2014-05-19T23:59:59";
DateTime dateTime = parser.parseDateTime(strDate.substring(0, 10));
Which will just parse 2014-05-19
part of String, this will cater for multiple time formats.