Date Formatting Using SimpleDateFormat


SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.

Example

Live Demo

import java.util.*;
import java.text.*;

public class DateDemo {

   public static void main(String args[]) {
      Date dNow = new Date( );
      SimpleDateFormat ft =        
      new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

      System.out.println("Current Date: " + ft.format(dNow));
   }
}

This will produce the following result −

Output

Current Date: Sun 2004.07.18 at 04:14:09 PM PDT

Simple DateFormat Format Codes

To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following

Character    
Description
Example
G
Era designator
AD
y
Year in four digits
2001
M
Month in year
July or 07
d
Day in month
10
h
An hour in A.M./P.M. (1~12)
12
H
An hour in a day (0~23)
22
m
Minute in hour
30
s
Second in minute
55
S
Millisecond
234
E
Day in week
Tuesday
D
Day in year
360
F
Day of week in the month
2 (second Wed. in July)
w
Week in year
40
W
Week in month
1
a
A.M./P.M. marker
PM
k
An hour in a day (1~24)
24
K
Hour in A.M./P.M. (0~11)
10
z
Time zone
Eastern Standard Time
'
Escape for text
Delimiter
"
Single quote
`

Updated on: 19-Jun-2020

693 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements