How to format Joda-Time DateTime to only mm/dd/yyyy?
Note that in JAVA SE 8 a new java.time (JSR-310) package was introduced. This replaces Joda time, Joda users are advised to migrate. For the JAVA SE ≥ 8 way of formatting date and time, see below.
Joda time
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 inputDateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");// Parsing the dateDateTime jodatime = dtf.parseDateTime(dateTime);// Format for outputDateTimeFormatter dtfOut = DateTimeFormat.forPattern("MM/dd/yyyy");// Printing the dateSystem.out.println(dtfOut.print(jodatime));
Standard Java ≥ 8
Java 8 introduced a new Date and Time library, making it easier to deal with dates and times. If you want to use standard Java version 8 or beyond, you would use a DateTimeFormatter. Since you don't have a time zone in your String
, a java.time.LocalDateTime or a LocalDate, otherwise the time zoned varieties ZonedDateTime and ZonedDate could be used.
// Format for inputDateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");// Parsing the dateLocalDate date = LocalDate.parse(dateTime, inputFormat);// Format for outputDateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");// Printing the dateSystem.out.println(date.format(outputFormat));
Standard Java < 8
Before Java 8, you would use the a SimpleDateFormat and java.util.Date
String dateTime = "11/15/2013 08:00:00";// Format for inputSimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");// Parsing the dateDate date7 = dateParser.parse(dateTime);// Format for outputSimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");// Printing the dateSystem.out.println(dateFormatter.format(date7));
I am adding this here even though the other answers are completely acceptable. JodaTime has parsers pre built in DateTimeFormat:
dateTime.toString(DateTimeFormat.longDate());
This is most of the options printed out with their format:
shortDate: 11/3/16shortDateTime: 11/3/16 4:25 AMmediumDate: Nov 3, 2016mediumDateTime: Nov 3, 2016 4:25:35 AMlongDate: November 3, 2016longDateTime: November 3, 2016 4:25:35 AM MDTfullDate: Thursday, November 3, 2016fullDateTime: Thursday, November 3, 2016 4:25:35 AM Mountain Daylight Time
DateTime date = DateTime.now().withTimeAtStartOfDay();date.toString("HH:mm:ss")