Yao Chen Yao Chen - 6 months ago 34
Java Question

How to format Joda-Time DateTime to only mm/dd/yyyy?

I have a string "

11/15/2013 08:00:00
", I want to format it to "
11/15/2013
", what is the correct
DateTimeFormatter
pattern?

I've tried many and googled and still unable to find the correct pattern.

edit: I am looking for Joda-Time
DateTimeFormatter
, not Java's SimpleDateFormat..

Answer

Create a DateTimeFormatter using DateTimeFormat.forPattern(String)

Using Joda time you would do it like this:

String dateTime = "11/15/2013 08:00:00";
// Format for input
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
// Parsing the date
DateTime jodatime = dtf.parseDateTime(dateTime);
// Format for output
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("MM/dd/yyyy");
// Printing the date
System.out.println(dtfOut.print(jodatime));

Also, if you wanted to use standard Java, you would do it like this:

// Format for input
SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
// Parsing the date
Date date = dateParser.parse(dateTime);
// Format for output
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
// Printing the date
System.out.println(dateFormatter.format(date));
Comments