text

Java SimpleDateFormat Example

In this example, we will show how to use the Java SimpleDateFormat class – java.text.SimpleDateFormat , so as to convert a Date into a formatted string or a string to a Date through a simple date format example.

You can make this conversion using the constructors provided by java.text.SimpleDateFormat class and some patterns, such as dd/MM/yyyy, dd-MM-yy and so on, so as to format the Date as you wish. We will show more examples of patterns and format symbols in the following sections.

1. Java SimpleDateFormat – Constructors

There are four constructors that you can use so as to create a java.text.SimpleDateFormat.

  • SimpleDateFormat()
    The simplest constructor which creates a java.text.SimpleDateFormat with a default pattern of date and a default locale.
  • SimpleDateFormat(String pattern)
    The constructor which creates a java.text.SimpleDateFormat with a given pattern and a default locale.
  • SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
    Constructs a java.text.SimpleDateFormat with the given pattern and specific date format symbols. DateFormatSymbols is a class for encapsulating localizable date-time formatting data, such as the names of the months, the names of the days of the week, and the time zone data.
  • SimpleDateFormat(String pattern, Locale locale)
    Constructs a java.text.SimpleDateFormat with the given pattern and a specific locale.

2. Pattern Syntax

LetterDate or Time ComponentPresentationExamples
GEra designatorTextAD
yYearYear1996; 96
YWeek yearYear2009; 09
MMonth in year (context sensitive)MonthJuly; Jul; 07
LMonth in year (standalone form)MonthJuly; Jul; 07
wWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
dDay in monthNumber10
FDay of week in monthNumber2
EDay name in weekTextTuesday; Tue
uDay number of week (1 = Monday, …, 7 = Sunday)Number1
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard Time; PST; GMT-08:00
ZTime zoneRFC 822 time zone-0800
XTime zoneISO 8601 time zone-08; -0800; -08:00

3. Pattern Examples

Date and Time PatternResult
"yyyy.MM.dd G 'at' HH:mm:ss z"2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy"Wed, Jul 4, '01
"h:mm a"12:08 PM
"hh 'o''clock' a, zzzz"12 o'clock PM, Pacific Daylight Time
"K:mm a, z"0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa"02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z"Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ"010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u"2001-W27-3

4. Example of SimpleDateFormat

Create a java class named SimpleDateFormatExample.java with the following code:

SimpleDateFormatExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.javacodegeeks.corejava.text;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
 
public class SimpleDateFormatExample {
    public static void main(String[] args) {
 
        Date curDate = new Date();
 
        SimpleDateFormat format = new SimpleDateFormat();
        String DateToStr = format.format(curDate);
        System.out.println("Default pattern: " + DateToStr);
 
        format = new SimpleDateFormat("yyyy/MM/dd");
        DateToStr = format.format(curDate);
        System.out.println(DateToStr);
 
        format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
        DateToStr = format.format(curDate);
        System.out.println(DateToStr);
 
        format = new SimpleDateFormat("dd MMMM yyyy zzzz", Locale.ENGLISH);
        DateToStr = format.format(curDate);
        System.out.println(DateToStr);
 
        format = new SimpleDateFormat("MMMM dd HH:mm:ss zzzz yyyy",
                Locale.ITALIAN);
        DateToStr = format.format(curDate);
        System.out.println(DateToStr);
 
        format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        DateToStr = format.format(curDate);
        System.out.println(DateToStr);
 
        format = new SimpleDateFormat("EEEEE dd MMMMM yyyy HH:mm:ss.SSSZ", new Locale("el", "GR"));
        DateToStr = format.format(curDate);
        System.out.println(DateToStr);
 
        try {
            Date strToDate = format.parse(DateToStr);
            System.out.println(strToDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Let’s explain the different formats of SimpleDateFormat class in the above code. Firstly, we create a Date object which is initialized with the current date and time. Then, we create different date formatters with different patterns, such as:

  • The default pattern, which shows the date in the form of month/day/year and the time using the 12-hour clock.
  • yyyy/MM/dd, which shows the date in the form of year/month/day. As we can observe, the pattern for the year has 4 letters, which means that the full form of the year will be used (e.g. 2014). Otherwise a short or abbreviated form is used if available.
  • dd-M-yyyy hh:mm:ss, which shows the date in the form of date-month-year (the month will be shown in the abbreviated form, as it has only one letter and not two as in the previous case) and futhermore, it shows the time (hour, minutes and seconds) while the hour is in am/pm format.
  • dd MMMM yyyy zzzz, which shows the date and the timezone in full format. We can observe that we also defined the locale of the date/time: Locale.ENGLISH or Locale.ITALIAN below.
  • E, dd MMM yyyy HH:mm:ss z, which shows the date, the day name of the week and the time (we can see that the hour is in capital, which means that the hour’s values here are between 0 – 23, as we use the 24-hour clock).
  • EEEEE dd MMMMM yyyy HH:mm:ss.SSSZ, which shows the day name, date, name of the month, year, 24H clock with seconds and 3 digits of milliseconds  and timezone.

You may notice that there is a slight but basic difference to the followings:

  • mm: representes the minutes.
  • MM: represents the Month.
  • dd: represents the day.
  • DD: represents the day in year (e.g. 189 out of 365).
  • hh: represents the hour’s value using the 12-hour clock.
  • HH: represents the hour’s value using the 24-hour clock.

Using all those formatters, we format dates as strings.

Finally, we show a reverse example, where we parse a string into date, using the parse() method.

If we run the above code, we will have the following results:

Output

1
2
3
4
5
6
7
8
Default pattern: 7/2/14 11:48 PM
2014/07/02
02-7-2014 11:48:37
02 July 2014 Eastern European Summer Time
luglio 02 23:48:37 Ora estiva dell'Europa orientale 2014
Wed, 02 Jul 2014 23:48:37 EEST
Wed Jul 02 23:48:37 EEST 2014
Τρίτη 22 Ιανουαρίου 2019 22:33:46.896+0200

5. Download the Source Code

This was an example of how to use the Java SimpleDateFormat class – java.text.SimpleDateFormat.

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

Last updated on Jan. 22, 2019

Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button