Formatting Date to String in Java

Learn to format a given date to a specified formatted string in Java. We will learn to use inbuilt patterns and custom patterns with DateTimeFormatter and SimpleDateFormat.

1. Formatting with DateTimeFormatter

Since Java 8, We can use DateTimeFormatter for all types of date and time related formatting tasks. This class is thread-safe and immutable so can be used in concurrent environments without risks.

To format a date instance to string, we first need to create DateTimeFormatter instance with desired output pattern and then use its format() method to format the date.

1.1. Creating DateTimeFormatter

We can create DateTimeFormatter in three ways:

  1. Using inbuilt patterns
  2. Using custom patterns using ofPattern() method
  3. Using localized styles with FormatStyle, such as long or medium
//Use inbuilt pattern constants
DateTimeFormatter inBuiltFormatter1 = DateTimeFormatter.ISO_DATE_TIME;
DateTimeFormatter inBuiltFormatter2 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
 
//Define your own custom patterns
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mma z");
 
//Using FormatStyle
DateTimeFormatter customFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);

Read More: DateTimeFormatter class

1.2. Formatting ZonedDateTime, LocalDateTime and LocalDate

The DateTimeFormatter class provides the methods String format(TemporalAccessor temporal) that can be used to format ZonedDateTime, LocalDateTime and LocalDate instances.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class FormattingDates {

  public static final String ZDT_PATTERN = "yyyy-MM-dd HH:mm:ss a z";
  public static final DateTimeFormatter ZDT_FORMATTER
      = DateTimeFormatter.ofPattern(ZDT_PATTERN);

  public static final String LDT_PATTERN = "yyyy-MM-dd HH:mm:ss a";
  public static final DateTimeFormatter LDT_FORMATTER
      = DateTimeFormatter.ofPattern(LDT_PATTERN);

  public static final String LD_PATTERN = "yyyy-MM-dd";
  public static final DateTimeFormatter LD_FORMATTER
      = DateTimeFormatter.ofPattern(LD_PATTERN);

  public static void main(String[] args) {
    String instanceString = ZDT_FORMATTER.format(ZonedDateTime.now());
    System.out.println(instanceString);

    String dateTimeString = LDT_FORMATTER.format(LocalDateTime.now());
    System.out.println(dateTimeString);

    String dateString = LD_FORMATTER.format(LocalDate.now());
    System.out.println(dateString);
  }
}

1.2. Creating Custom Patterns

The custom pattern string can have any number of pre-defined letters and symbols which have their own meaning. The most used symbols are : Y, M, D, h, m, and s.

Also, note that the number of repetitions of a letter in the pattern also have different meanings. For example, “MMM” gives “Jan,” whereas “MMMM” gives “January.”

Let’s see these symbols for quick reference.

SymbolMeaningTypeExample
GEraStringAD; Anno Domini
yYear of eraYear2004 or 04
uYear of eraYearSimilar to ‘y’ but returns proleptic year.
DDay of yearNumber235
M / LMonth of yearNumber / String7 or 07; J or Jul or July
dDay of monthNumber21
Q / qQuarter of yearNumber / String3 or 03; Q3 or 3rd quarter
YWeek based yearYear1996 or 96
wWeek of week based yearNumber32
WWeek of monthNumber3
e / cLocalized day of weekNumber / String2 or 02; T or Tue or Tuesday
EDay of weekStringT or Tue or Tuesday
FWeek of monthNumber3
aam / pm of the dayStringPM
hClock hour of am pm (1-12)Number12
KHour of am pm (0-11)Number0
kClock hour of am pm (1-24)Number15
HHour of day (0-23)Number15
mMinute of hourNumber30
sSecond of minuteNumber55
SFraction of secondFraction978
AMillisecond of dayNumber1234
nNanosecond of secondNumber987654321
NNanosecond of dayNumber1234560000
VTime zone IDZone-idAmerica/Los_Angeles or Z or –08:30
zTime zone nameZone-namePacific Standard Time or PST
XZone offset Z for zeroOffset-XZ or –08 or –0830 or –08:30 or –083015 or –08:30:15
xZone offsetOffset-x+0000 or –08 or –0830 or –08:30 or –083015 or –08:30:15
ZZone offsetOffset-Z+0000 or –0800 or –08:00
OLocalized zone offsetOffset-OGMT+8 or GMT+08:00 or UTC–08:00
pPad nextPad modifier1

1.4. UnsupportedTemporalTypeException

If we try to use DateTimeFormatter with pattern that is not supported by the date-time instance, its format() will throw this exception.

For example, if we try to format LocalDate with pattern containing hours and minutes then this exception will be thrown, because LocalDate does not support any time information.

public static final String TIMESTAMP_PATTERN
	= "yyyy-MM-dd HH:mm:ss a";
public static final DateTimeFormatter FOMATTER
	= DateTimeFormatter.ofPattern(TIMESTAMP_PATTERN);

String formmatedString = FOMATTER.format( LocalDate.now() );

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
	at java.base/java.time.LocalDate.get0(LocalDate.java:709)
	at java.base/java.time.LocalDate.getLong(LocalDate.java:688)
...

2. Formatting with SimpleDateFormat

In case you are still stuck at Java 7 and can’t upgrade due to some legacy application’s dependencies, you can use SimpleDateFormat for date formatting in a locale-sensitive manner.

Though SimpleDateFormat is not thread-safe or immutable, still, it serves the purpose pretty well. Do not use this class in a multi-threaded environment without added synchronization.

2.1. Creating SimpleDateFormat

SimpleDateFormat provides the following constructors:

  • SimpleDateFormat(pattern): uses the given pattern and the default date format symbols for the default locale.
  • SimpleDateFormat(pattern, locale): uses the given pattern and the default date format symbols for the given locale.
  • SimpleDateFormat(pattern, formatSymbols): uses the given pattern and date format symbols.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");

SimpleDateFormat simpleDateFormat =new SimpleDateFormat("MM-dd-yyyy", new Locale("fr", "FR"));

DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
symbols.setAmPmStrings(new String[] { "AM", "PM" });  //Override specific symbols and retaining others
sdf.setDateFormatSymbols(symbols);

2.2. Convert Date to String

Now we can use the constructed SimpleDateFormat instance to format a given Date object to a string.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String formattedDate = sdf.format(new Date());
System.out.println(formattedDate);

String pattern = "EEEEE MMMMM yyyy HH:mm:ss.SSSZ";
SimpleDateFormat sdfWithLocale =new SimpleDateFormat(pattern,
    new Locale("fr", "FR"));
String date = sdfWithLocale.format(new Date());
System.out.println(date);

DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
symbols.setAmPmStrings(new String[] { "AM", "PM" });
sdf.setDateFormatSymbols(symbols);
formattedDate = sdf.format(new Date());
System.out.println(formattedDate);

Program Output.

2022-02-17 21:57:01 pm
jeudi février 2022 21:57:01.644+0530
2022-02-17 21:57:01 PM

3. Conclusion

If you have the liberty to upgrade a Java 7 application to the latest Java version, please do it on priority. The thread-safe and immutable nature of DateTimeFormatter is a huge win in terms of performance over SimpleDateFormat.

Both classes provide format() example which is used to format the date objects into a string.

Happy Learning !!

Sourcecode Download

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.