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.example.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 an the example result of our program:
Pattern = E MM/dd/yyyy HH:mm:ss.SSS
Default = Mon 07/22/2019 13:50:28.502
Germany = Mo 07/22/2019 13:50:28.502
French = lun. 07/22/2019 13:50:28.502
Japanese = 月 07/22/2019 13:50:28.502
fullDate = Monday, July 22, 2019
longDate = July 22, 2019
mediumDate = Jul 22, 2019
shortDate = 7/22/19
dd/MM/yyyy = 22/07/2019
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.3/joda-time-2.10.3.jar -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.3</version>
</dependency>
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020