Monday 30 May 2016

Date Time Formatting in Java



/**
@author : Charudatta Ekbote
*/

Following Code demonstrates different sample outputs generated using java's DateTime formatting options  

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

public class DateFormatDemo
{
public static void main(String[] args)
{
Date date = new Date();

System.out.println(date); // sample output format: Mon May 30 19:48:40 IST 2016

SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/YYYY-E");
System.out.println(sdf.format(date) ); // sample output format: 30/May/2016-Mon

sdf = new SimpleDateFormat("dd/MM/YYYY");
System.out.println(sdf.format(date) ); // sample output format: 30/05/2016-Mon

sdf = new SimpleDateFormat("E");
System.out.println(sdf.format(date) ); // sample output format: Mon

sdf = new SimpleDateFormat("H:m:s");
System.out.println(sdf.format(date) ); // sample output format: 19:44:29

sdf = new SimpleDateFormat("K:m:sa");
System.out.println(sdf.format(date) ); // sample output format: 7:44:29PM
}
}


Following is the List of Options used by Java to format Date and Time :


Letter
Date or Time Component
Presentation
Examples
G
Era designator
AD
y
Year
1996; 96
Y
Week year
2009; 09
M
Month in year
July; Jul; 07
w
Week in year
27
W
Week in month
2
D
Day in year
189
d
Day in month
10
F
Day of week in month
2
E
Day name in week
Tuesday; Tue
u
Day number of week (1 = Monday, ..., 7 = Sunday)
1
a
Am/pm marker
PM
H
Hour in day (0-23)
0
k
Hour in day (1-24)
24
K
Hour in am/pm (0-11)
0
h
Hour in am/pm (1-12)
12
m
Minute in hour
30
s
Second in minute
55
S
Millisecond
978
z
Time zone
Pacific Standard Time; PST; GMT-08:00




No comments:

Post a Comment