How to Format Dates in Java

Java is a versatile programming language. If you use the toString() method to convert a LocalDate to a string, you get a string such as 2014-10-31. What if you want to display the date in a different format, such as 10-31-2014 or October 31, 2014?

To accomplish that, you can use the format method of the LocalDate class along with a custom formatter you create using the DateTimeFormatter class. To specify the format you want to use, you pass the DateTimeFormatter class a pattern string, using the formatting symbols listed in Table 5-4.

Format pattern Explanation
y Year (two or four digits)
M Month (one or two digits or three or more letters)
d Day of month (such as 1, 28)
H Hour
m Minute
s Second (0-to 59)
h Clock hour (1 to 12)
a AM or PM
V Time zone ID (such as America/Los_Angeles)
z Time zone name (such as Pacific Daylight Time)

The easiest way to create a DateTimeFormatter object is to use the static ofPattern method along with a pattern string. For example:

DateTimeFormatter formatter;
formatter = DateTimeFormatter.ofPattern("dd MMM YYYY");

This formatter produces dates formatted like 04 SEP 2014. You can then use the formatter to produce a formatted date string like this:

LocalDate date = LocalDate.now();
String formattedDate = date.format(formatter);

Here's a simple program that prints the current date in several different formats:

import java.util.*;
import java.time.*;
import java.time.format.*;
public class FormatDateTime
{
 public static void main(String[] args)
 {
  LocalDateTime now = LocalDateTime.now();
  printDate(now, "YYYY-MM-dd");
  printDate(now, "MM-dd-YYYY");
  printDate(now, "dd MMM YYYY");
  printDate(now, "MMMM d, YYYY");
  printDate(now, "HH:mm");
  printDate(now, "h:mm a");
 }
 public static void printDate(LocalDateTime date, String pattern)
 {
  DateTimeFormatter f;
  f = DateTimeFormatter.ofPattern(pattern);
  pattern = (pattern + "    ").substring(0, 14);
  System.out.println(pattern + " " + date.format(f));
 }
}

When you run this program, you'll get console output that resembles this:

YYYY-MM-dd  2013-10-09
MM-dd-YYYY  10-09-2013
dd MMM YYYY 09 Oct 2013
MMMM d, YYYY October 9, 2013
HH:mm   20:29
h:mm a   8:29 PM

Did you notice the cool formatting trick? You can force the System.out.println() patterns to print 14-character long strings so all the dates would line up The padding is accomplished by this slick line of code:

pattern = (pattern + "    ").substring(0, 14);

Here a string of 14 spaces is added to the pattern string, then a 14-character long substring is taken starting at the first character. The nice spacing in the output makes it easier for you to see the effect of each of the pattern strings.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.