Home » Core Java » Java Date Format Example

About Rajagopal ParthaSarathi

Rajagopal works in software industry solving enterprise-scale problems for customers across geographies specializing in open source distributed platforms. He currently holds masters in computer science with focus on cloud computing from Illinois Institute of Technology. His current interests include but not limited to machine learning and big data engineering.

Java Date Format Example

In this article, we will check the options available on Java Date Format.

1. Introduction

Java has multiple packages providing various utility functions to make developer’s job easier. One such is the java.text package which includes utility classes for parsing and formatting numbers and dates, along with utility classes for building other kinds of parsers. The java.text.DateFormatclass and its concrete subclass java.text.SimpleDateFormat provide a convenient way to convert strings with the date and/or time info to and from java.util.Date objects.

2. Java Date Format

This is an abstract class used to provide an interface over most of the date related utilities. The most common implementation is SimpleDateFormat. The way we initialize the class is by calling the method as below

Before understanding the various ways of initializing, we can look at three different flags which control the display format of date and time

  • SHORT – This displays the time or date in the shortest form visible. For example, Time is displayed as 10:14 pm while the Date is displayed as 22/6/19
  • MEDIUM – This is the default mode of display. In this mode, Time is displayed as 10:14:53 pm while the Date is displayed as 22 Jun, 2019
  • LONG – This displays the time or date in the clearest form available. For example, Time is displayed as 10:14:53 PM IST including the timezone while the Date is displayed as 22 June, 2019. In Medium, Month is abbreviated to 3 characters while here it is expanded.
  • FULL – This involves no change for Time from LONG but the Date is displayed as Saturday, 22 June, 2019 including the week of the day.
Date Initialization
 
  DateFormat format = DateFormat.getInstance();
  DateFormat dateTimeFormat = DateFormat.getDateTimeInstance();
  DateFormat timeFormat = DateFormat.getTimeInstance();
  • The first one initializes both the date and time instance with value as SHORT
  • The second one initializes both the date and time instance with value as MEDIUM
  • The final one initializes only the time instance with value as MEDIUM

We can see the result by running the example which might make it clear

Date With default format
  
Date now = new Date();
System.out.println(" String version of Date. " + now.toString());
System.out.println(" DateTimeWithShort. " + DateFormat.getInstance().format(now));
System.out.println(" TimeWithMedium. " + DateFormat.getTimeInstance().format(now));
System.out.println(" DateTimeWithMedium. " + DateFormat.getDateTimeInstance().format(now));

This produces the following output

 String version of Date. Sat Jun 22 22:32:24 IST 2019
 DateTimeWithShort. 22/6/19 10:32 PM
 TimeWithMedium. 10:32:24 PM
 DateTimeWithMedium. 22 Jun, 2019 10:32:24 PM
 

The format takes in a date parameter which can be any valid date. For our example, We have considered the current time using new Date(). Also we can provide the various flags discussed above as input to the methods getTimeInstance and getDateTimeInstance. We will see couple of examples of the same with their corresponding outputs below.

Date With predefined formats
 
System.out.println("TimeWithShort . " + DateFormat.getTimeInstance(DateFormat.SHORT).format(now));
System.out.println("TimeWithLong. " + DateFormat.getTimeInstance(DateFormat.LONG).format(now));
System.out.println("DTML. " + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(now));
System.out.println("DTMF. " + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL).format(now));
System.out.println("DTLL. " + DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(now));
System.out.println("DTLF. " + DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL).format(now));
TimeWithShort . 10:43 PM
TimeWithLong. 10:43:27 PM IST
DTML. 22 Jun, 2019 10:43:27 PM IST
DTMF. 22 Jun, 2019 10:43:27 PM IST
DTLL. 22 June, 2019 10:43:27 PM IST
DTLF. 22 June, 2019 10:43:27 PM IST
 

The textFormat package also provides utility for extracting date from a string or other types. Let us see a simple example of parsing date with a string.

Date Parsing
 try {
 DateFormat format =    DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);
 Date parsedDate = format.parse("22/6/19 10:43 PM");
 Calendar cal = Calendar.getInstance();
 cal.setTime(parsedDate);
 cal.add(Calendar.DATE,5);
 System.out.println("Date Result. "+cal.getTime().toString());
} catch (ParseException e) {
  e.printStackTrace();
}
  • We are creating DateFormat instance with SHORT flag.
  • We parse the input string using the parse method.
  • After parsing, the extracted date is set to calendar instance.
  • 5 days are added to the original date
  • Final result is printed back to the console.

A thing to note is that the date string should adhere to the format pattern specified. If not parse exception is thrown, when the string is being parsed..

3. SimpleDateFormat

In the above example, the format flags specified is very limited and cannot handle a variety of other different formats. Even date.toString() cannot be handled with the existing format flags. This is where SimpleDateFormat kicks in and provides other formatting options. The class can be initialized as shown below

Date With default format
Date now = new Date();
String pattern = "G";
DateFormat simpleDateFormat = new SimpleDateFormat(pattern);
System.out.println(simpleDateFormat.format(now));
  • We specify a pattern format to be used. We can see all the patterns in table below
  • In next step, we provide the pattern to be compiled by passing the pattern to an instance of SimpleDateFormat.
  • The final step is formatting the date. Date is displayed based on the string format specified.

The following are the other format specifiers available in SimpleDateFormat to extend the functionality of the date parsing and formatting.

Pattern
(substitute
in code
above)
DescriptionOutput
GUsed to specify the eraAD
yspecifies the year2019
yyspecifies the year in 2 digit19
yyyyypads with zero for the extra y02019
M (or) MMMonth specifier in number7 (or) 07 (or) 12
MMMMonth specifier in abbreviated stringJul
MMMMFull name of the monthJuly
m (or) mmDisplays the minute09 (or) 43
d (or) ddDisplays the day of the month7 (or) 07 (or) 23
h (or) hhDisplays the hour(1-12)5 (or) 05 (or) 11
H (or) HHDisplays the hour(0-23)17 (or) 01 (or) 1
k (or) kkDisplays the hour(1-24)1 (or) 01 (or) 24
K (or) KKDisplays the hour (0-11)1 (or) 01 (or) 11
S (or) SS (or) SSSMillisecond (0-999)7 (or) 07 (or) 007
E (or) EEEEDay in WeekThu (or) Thursday
DDay in Year178
FDay of Week in number1 indicates Monday
w (or) wwWeek for an year26
WWeek in month5
aAM/PMAM
z(or)zzzzzDisplay the current time zoneIST (or) Indian Standard Time

We can follow the entire format specifiers with an example.

Date With Full Custom format
try {
    DateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM yyyy G hh:mm:SS zzz");
    String result = simpleDateFormat.format(now);
    System.out.println("Date String "+result);
    System.out.println("ParsedResult "+simpleDateFormat.parse(result));
} catch (ParseException e) {
    e.printStackTrace();
}

The above displays the date in the format 25 June 2019 AD 05:17:960 IST. We can parse the string date back into original date form. Both of them have been illustrated with above example

In this article, we saw the various ways date can be formatted and also the ways of parsing a string back to date.

4. Download the Source code

Download
You can download the full source code of this example here: Java Date Format Example

Last updated on Aug. 29, 2019

(+5 rating, 5 votes)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Avi Abrami Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Avi Abrami
Guest
Avi Abrami

Seriously? An article written five years after the release of java 8 with the new date-time API which talks about the pre java 8 date and time classes?