How do I format DateTime object in Joda-Time?

The example show you how to format the string representation of a date. In Joda we can use the DateTime‘s class toString() method. The method accept the pattern of the date format and the locale information.

package org.kodejava.joda;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import java.util.Locale;

public class FormattingDemo {
    // Define the date format pattern.
    private static final String pattern = "E MM/dd/yyyy HH:mm:ss.SSS";

    public static void main(String[] args) {
        // Creates a new instance of DateTime object.
        DateTime dt = DateTime.now();

        // Print out the date as a formatted string using the defined
        // Locale information.
        System.out.println("Pattern  = " + pattern);
        System.out.println("Default  = " + dt.toString(pattern));
        System.out.println("Germany  = " + dt.toString(pattern, Locale.GERMANY));
        System.out.println("French   = " + dt.toString(pattern, Locale.FRENCH));
        System.out.println("Japanese = " + dt.toString(pattern, Locale.JAPANESE));

        // Using predefined format from DateTimeFormat class.
        System.out.println("fullDate   = " + dt.toString(DateTimeFormat.fullDate()));
        System.out.println("longDate   = " + dt.toString(DateTimeFormat.longDate()));
        System.out.println("mediumDate = " + dt.toString(DateTimeFormat.mediumDate()));
        System.out.println("shortDate  = " + dt.toString(DateTimeFormat.shortDate()));
        System.out.println("dd/MM/yyyy = " + dt.toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
    }
}

Here are the example result of our program:

Pattern  = E MM/dd/yyyy HH:mm:ss.SSS
Default  = Fri 10/29/2021 06:49:32.491
Germany  = Fr. 10/29/2021 06:49:32.491
French   = ven. 10/29/2021 06:49:32.491
Japanese = 金 10/29/2021 06:49:32.491
fullDate   = Friday, October 29, 2021
longDate   = October 29, 2021
mediumDate = Oct 29, 2021
shortDate  = 10/29/21
dd/MM/yyyy = 29/10/2021

Maven Dependencies

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.5</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.