DateFormat helps you to format and parse dates for any locale. DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT.
- SHORT is completely numeric, such as 12.13.52 or 3:30pm
- MEDIUM is longer, such as Jan 12, 1952
- LONG is longer, such as January 12, 1952 or 3:30:32pm
- FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.
Ex:
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date now = new Date();
DateFormat defaultDf = DateFormat.getDateInstance();
//DateFormat defaultDf = DateFormat.getTimeInstance();
//By above line you can get also the time instance
DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat mediumDf = DateFormat.getDateInstance(DateFormat.MEDIUM);
DateFormat longDf = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat fullDf = DateFormat.getDateInstance(DateFormat.FULL);
System.out.println(" 1. " + defaultDf.format(now));
System.out.println(" 2. " + shortDf.format(now));
System.out.println(" 3. " + mediumDf.format(now));
System.out.println(" 4. " + longDf.format(now));
System.out.println(" 5. " + fullDf.format(now));
}
}
The output is
1. Jun 20, 2008
2. 6/20/08
3. Jun 20, 2008
4. June 20, 2008
5. Friday, June 20, 2008
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.
Ex:
import java.text.SimpleDateFormat;
import java.util.Date;
public class demo {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("MMM dd yyyy");
SimpleDateFormat format3 = new SimpleDateFormat("MM dd yyyy");
System.out.println("1. " + format1.format(now));
System.out.println("1. " + format2.format(now));
System.out.println("1. " + format3.format(now));
}
}
Representation of different formats in SimpleDateFormat:
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
No comments:
Post a Comment