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.

Symbol
Meaning
Type
Example
G
Era
String
AD; Anno Domini
y
Year of era
Year
2004 or 04
u
Year of era
Year
Similar to ‘y’ but returns proleptic year.
D
Day of year
Number
235
M / L
Month of year
Number / String
7 or 07; J or Jul or July
d
Day of month
Number
21
Q / q
Quarter of year
Number / String
3 or 03; Q3 or 3rd quarter
Y
Week based year
Year
1996 or 96
w
Week of week based year
Number
32
W
Week of month
Number
3
e / c
Localized day of week
Number / String
2 or 02; T or Tue or Tuesday
E
Day of week
String
T or Tue or Tuesday
F
Week of month
Number
3
a
am / pm of day
String
PM
h
Clock hour of am pm (1-12)
Number
12
K
Hour of am pm (0-11)
Number
0
k
Clock hour of am pm (1-24)
Number
15
H
Hour of day (0-23)
Number
15
m
Minute of hour
Number
30
s
Second of minute
Number
55
S
Fraction of second
Fraction
978
A
Millisecond of day
Number
1234
n
Nanosecond of second
Number
987654321
N
Nanosecond of day
Number
1234560000
V
Time zone ID
Zone-id
America/Los_Angeles or Z or –08:30
z
Time zone name
Zone-name
Pacific Standard Time or PST
X
Zone offset Z for zero
Offset-X
Z or –08 or –0830 or –08:30 or –083015 or –08:30:15
x
Zone offset
Offset-x
+0000 or –08 or –0830 or –08:30 or –083015 or –08:30:15
Z
Zone offset
Offset-Z
+0000 or –0800 or –08:00
O
Localized zone offset
Offset-O
GMT+8 or GMT+08:00 or UTC–08:00
p
Pad next
Pad modifier
1

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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.