Search code examples
javajodatimedate-format

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..


Solution

  • 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 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));
    

    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 input
    DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
    // Parsing the date
    LocalDate date = LocalDate.parse(dateTime, inputFormat);
    // Format for output
    DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    // Printing the date
    System.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 input
    SimpleDateFormat dateParser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    // Parsing the date
    Date date7 = dateParser.parse(dateTime);
    // Format for output
    SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
    // Printing the date
    System.out.println(dateFormatter.format(date7));