HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Date Time / Java – Date Formatting

Java – Date Formatting

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

1. DateTimeFormatter – Java 8

In Java 8, We can use DateTimeFormatter for all types of date and time related formatting tasks. It is thread-safe or immutable so can be used in concurrent environment without risks.

1.1. Date format example

Java 8 example to format LocalDateTime and LocalDate instances in desired string patterns.

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

public class DateFormatting 
{
	public static void main(String[] args) 
	{
		String dateTimeString = formatLocalDateTime(LocalDateTime.now()); 
		System.out.println(dateTimeString);  //2020-05-08 23:17:22 PM
		
		String dateString = formatLocalDate(LocalDate.now()); 
		System.out.println(dateString);  //2020-05-08
	}

	//Format LocalDateTime to String
	
	public static final String TIMESTAMP_PATTERN = "yyyy-MM-dd HH:mm:ss a"; 
	public static final DateTimeFormatter LDT_FOMATTER 
                      = DateTimeFormatter.ofPattern(TIMESTAMP_PATTERN);

	private static String formatLocalDateTime(LocalDateTime ldt)
	{
		return LDT_FOMATTER.format(ldt);
	}
	
	//Format LocalDate to String

	public static final String DATE_PATTERN = "yyyy-MM-dd"; 
	public static final DateTimeFormatter LD_FOMATTER 
                      = DateTimeFormatter.ofPattern(DATE_PATTERN);
	
	private static String formatLocalDate(LocalDate ld)
	{
		return LD_FOMATTER.format(ld);
	}
}

1.2. Pattern String

DateTimeFormatter provides two ways to define patterns:

  • Nearly 15 inbuilt predefined patterns e.g. ISO_LOCAL_DATE (‘2011-12-03’) or ISO_OFFSET_DATE_TIME (‘2011-12-03T10:15:30+01:00’)
  • any custom pattern using DateTimeFormatter.ofPattern(pattern)

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 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.3. 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 thn 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)
	at java.base/java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:308)
	at java.base/java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2704)
	at java.base/java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2343)
	at java.base/java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1847)
	at java.base/java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1821)
	at com.howtodoinjava.core.datetime.DateFormatting.formatLocalDate(DateFormatting.java:33)
	at com.howtodoinjava.core.datetime.DateFormatting.main(DateFormatting.java:21)

2. SimpleDateFormat – Java 7

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.

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

import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaDateValidations 
{
	public static final String TIMESTAMP_PATTERN 
							= "yyyy-MM-dd HH:mm:ss a"; 

	public static void main(String[] args) 
	{
		SimpleDateFormat sdf = new SimpleDateFormat(TIMESTAMP_PATTERN);
		
		Date date = new Date();
		
		String formattedDate = sdf.format(date);
		System.out.println(formattedDate);		//2020-05-09 00:32:28 AM
	}
}

3. Conclusion

If you have the liberty to upgrade a Java 7 application to Java 8, 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 are used to format the date objects into string.

Drop me your questions and suggestions related to java date formatter example in comments.

Happy Learning !!

Sourcecode Download

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java Date Time Tutorial

  • Java – Date Time APIs
  • Java – Date Parsing
  • Java – Date Formatting
  • Java 8 – LocalDate
  • Java 8 – LocalTime
  • Java 8 – LocalDateTime
  • Java 8 – ZonedDateTime
  • Java 8 – Period
  • Java 8 – DateTimeFormatter
  • Java 8 – TemporalAdjusters
  • Java 8 – TemporalQuery
  • Java 8 – DayOfWeek
  • Java – Date
  • Java – Locale

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)