DateFormat and SimpleDateFormat Examples
Version 1.1 of Java introduced thejava.text
package, which included utility classes for parsing and formatting
numbers and dates, along with utility classes for building other kinds
of parsers.Default date formats
The
java.text.DateFormat class, and its concrete subclass java.text.SimpleDateFormat, provide a convenient way to convert strings with date and/or time info to and from java.util.Date objects. Figure 1 shows an example of using default DateFormat objects to format a date in a variety of ways:
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample1 {
public static void main(String[] args) {
// Make a new Date object. It will be initialized to the current time.
Date now = new Date();
// See what toString() returns
System.out.println(" 1. " + now.toString());
// Next, try the default DateFormat
System.out.println(" 2. " + DateFormat.getInstance().format(now));
// And the default time and date-time DateFormats
System.out.println(" 3. " + DateFormat.getTimeInstance().format(now));
System.out.println(" 4. " +
DateFormat.getDateTimeInstance().format(now));
// Next, try the short, medium and long variants of the
// default time format
System.out.println(" 5. " +
DateFormat.getTimeInstance(DateFormat.SHORT).format(now));
System.out.println(" 6. " +
DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now));
System.out.println(" 7. " +
DateFormat.getTimeInstance(DateFormat.LONG).format(now));
// For the default date-time format, the length of both the
// date and time elements can be specified. Here are some examples:
System.out.println(" 8. " + DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT).format(now));
System.out.println(" 9. " + DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(now));
System.out.println("10. " + DateFormat.getDateTimeInstance(
DateFormat.LONG, DateFormat.LONG).format(now));
}
}
DateFormat objects to format a Date object.> java DateFormatExample1 1. Tue Nov 04 20:14:11 EST 2003 2. 11/4/03 8:14 PM 3. 8:14:11 PM 4. Nov 4, 2003 8:14:11 PM 5. 8:14 PM 6. 8:14:11 PM 7. 8:14:11 PM EST 8. 11/4/03 8:14 PM 9. Nov 4, 2003 8:14 PM 10. November 4, 2003 8:14:11 PM EST
DateFormat objects retrieved from the static getInstance(), getTimeInstance(), and getDateTimeInstance() methods can also be used for parsing String objects to produce Date objects. Figure 3 shows a simple example of this.import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class DateFormatExample2 {
public static void main(String[] args) {
// Make a String that has a date in it, with MEDIUM date format
// and SHORT time format.
String dateString = "Nov 4, 2003 8:14 PM";
// Get the default MEDIUM/SHORT DateFormat
DateFormat format =
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT);
// Parse the date
try {
Date date = format.parse(dateString);
System.out.println("Original string: " + dateString);
System.out.println("Parsed date : " +
date.toString());
}
catch(ParseException pe) {
System.out.println("ERROR: could not parse date in string \"" +
dateString + "\"");
}
}
}
DateFormat objects to parse a String> java DateFormatExample2 Original string: Nov 4, 2003 8:14 PM Parsed date : Tue Nov 04 20:14:00 EST 2003
parse method throws an exception if a date matching
the format cannot be parsed. In the code shown in Figure 3, the string
matches the format exactly. To see what happens when a bad string is
encountered, the class in Figure 5 reads and attempts to parse input
until a blank line (or a Control-D) is entered.import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DateFormatExample3 {
public static void main(String[] args) {
// Get the default MEDIUM/SHORT DateFormat
DateFormat format =
DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT);
// Read and parse input, stopping on a blank input line
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("ENTER DATE STRING: ");
String dateString = reader.readLine();
while ((dateString != null) && (dateString.length() > 0)) {
// Parse the date
try {
Date date = format.parse(dateString);
System.out.println("Original string: " + dateString);
System.out.println("Parsed date : " +
date.toString());
System.out.println(); // Skip a line
}
catch(ParseException pe) {
System.out.println(
"ERROR: could not parse date in string \"" +
dateString + "\"");
}
// Read another string
System.out.print("ENTER DATE STRING: ");
dateString = reader.readLine();
}
}
catch(IOException ioe) {
System.out.println("I/O Exception: " + ioe);
}
}
}
> java DateFormatExample3 ENTER DATE STRING: Nov 4, 2003 8:14 PM Original string: Nov 4, 2003 8:14 PM Parsed date : Tue Nov 04 20:14:00 EST 2003 ENTER DATE STRING: Nov 4, 2003 8:14 ERROR: could not parse date in string "Nov 4, 2003 8:14 " ENTER DATE STRING: Nov 4, 2003 8:14 AM Original string: Nov 4, 2003 8:14 AM Parsed date : Tue Nov 04 08:14:00 EST 2003 ENTER DATE STRING: November 4, 2003 8:14 AM Original string: November 4, 2003 8:14 AM Parsed date : Tue Nov 04 08:14:00 EST 2003 ENTER DATE STRING: Nov 4, 2003 20:14 PM Original string: Nov 4, 2003 20:14 PM Parsed date : Wed Nov 05 08:14:00 EST 2003 ENTER DATE STRING: Nov 4, 2003 20:14 ERROR: could not parse date in string "Nov 4, 2003 20:14" ENTER DATE STRING:
DateFormat actually gives you a small amount of control over leniency in parsing. The default DateFormat instances are lenient by default, but invoking format.setLenient(false);
in the example in Figure 5 would cause the “20:14 PM” example (in
Figure 6) to fail, though it will still accept “November” or “Nov”.Using SimpleDateFormat for custom date formatting and parsing
The default
DateFormat instances returned by the static methods in the DateFormat
class may be sufficient for many purposes, but clearly do not cover all
possible valid or useful formats for dates. For example, notice that in
Figure 2, none of the DateFormat-generated strings (numbers 2 – 9) match the format of the output of the Date class’s toString() method. This means that you cannot use the default DateFormat instances to parse the output of toString(), something that might be useful for things like parsing log data.The
SimpleDateFormat lets you build custom formats.
Dates are constructed with a string that specifies a pattern for the
dates to be formatted and/or parsed. From the SimpleDateFormat
JavaDocs, the characters in Figure 7 can be used in date formats. Where
appropriate, 4 or more of the character will be interpreted to mean
that the long format of the element should be used, while fewer than 4
mean that a short format should be used.| Symbol | Meaning | Type | Example |
| G | Era | Text | “GG” -> “AD” |
| y | Year | Number | “yy” -> “03″ “yyyy” -> “2003″ |
| M | Month | Text or Number | “M” -> “7″ “M” -> “12″ “MM” -> “07″ “MMM” -> “Jul” “MMMM” -> “December” |
| d | Day in month | Number | “d” -> “3″ “dd” -> “03″ |
| h | Hour (1-12, AM/PM) | Number | “h” -> “3″ “hh” -> “03″ |
| H | Hour (0-23) | Number | “H” -> “15″ “HH” -> “15″ |
| k | Hour (1-24) | Number | “k” -> “3″ “kk” -> “03″ |
| K | Hour (0-11 AM/PM) | Number | “K” -> “15″ “KK” -> “15″ |
| m | Minute | Number | “m” -> “7″ “m” -> “15″ “mm” -> “15″ |
| s | Second | Number | “s” -> “15″ “ss” -> “15″ |
| S | Millisecond (0-999) | Number | “SSS” -> “007″ |
| E | Day in week | Text | “EEE” -> “Tue” “EEEE” -> “Tuesday” |
| D | Day in year (1-365 or 1-364) | Number | “D” -> “65″ “DDD” -> “065″ |
| F | Day of week in month (1-5) | Number | “F” -> “1″ |
| w | Week in year (1-53) | Number | “w” -> “7″ |
| W | Week in month (1-5) | Number | “W” -> “3″ |
| a | AM/PM | Text | “a” -> “AM” “aa” -> “AM” |
| z | Time zone | Text | “z” -> “EST” “zzz” -> “EST” “zzzz” -> “Eastern Standard Time” |
| ‘ | Excape for text | Delimiter | “‘hour’ h” -> “hour 9″ |
| ” | Single quote | Literal | “ss”SSS” -> “45’876″ |
SimpleDateFormatSimpleDateFormat (“m”, “s”, “S”).Using the syntax from Figure 7, we can now make a
SimpleDateFormat that can read the output of Date.toString(). Figure 8 shows an example this:import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class DateFormatExample4 {
public static void main(String[] args) {
// Make a new Date object. It will be initialized to the
// current time.
Date now = new Date();
// Print the result of toString()
String dateString = now.toString();
System.out.println(" 1. " + dateString);
// Make a SimpleDateFormat for toString()'s output. This
// has short (text) date, a space, short (text) month, a space,
// 2-digit date, a space, hour (0-23), minute, second, a space,
// short timezone, a final space, and a long year.
SimpleDateFormat format =
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
// See if we can parse the output of Date.toString()
try {
Date parsed = format.parse(dateString);
System.out.println(" 2. " + parsed.toString());
}
catch(ParseException pe) {
System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
}
// Print the result of formatting the now Date to see if the result
// is the same as the output of toString()
System.out.println(" 3. " + format.format(now));
}
}
The output shows three identical strings:> java DateFormatExample4 1. Tue Nov 04 21:53:43 EST 2003 2. Tue Nov 04 21:53:43 EST 2003 3. Tue Nov 04 21:53:43 EST 2003
Date.toString() outputJava Date and Calendar examples
This tutorial shows you how to work with
java.util.Date and java.util.Calendar.1. Java Date Examples
Few examples to work with
Date APIs.
Example 1.1 – Convert Date to String.
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
String date = sdf.format(new Date());
System.out.println(date); //15/10/2013
Example 1.2 – Convert String to Date.
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "31-08-1982 10:20:56";
Date date = sdf.parse(dateInString);
System.out.println(date); //Tue Aug 31 10:20:56 SGT 1982
P.S Refer to this – SimpleDateFormat JavaDoc for detail date and time patterns.
Example 1.3 – Get current date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2013/10/15 16:16:39
Example 1.4 – Convert Calendar to Date
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
2. Java Calendar Examples
Few examples to work with
Calendar APIs.
Example 2.1 – Get current date time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,0,31);
System.out.println(sdf.format(calendar.getTime()));
Output
2013 Jan 31 00:00:00
Example 2.2 – Simple Calendar example
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,1,28,13,24,56);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);
int hour = calendar.get(Calendar.HOUR); // 12 hour clock
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int millisecond= calendar.get(Calendar.MILLISECOND);
System.out.println(sdf.format(calendar.getTime()));
System.out.println("year \t\t: " + year);
System.out.println("month \t\t: " + month);
System.out.println("dayOfMonth \t: " + dayOfMonth);
System.out.println("dayOfWeek \t: " + dayOfWeek);
System.out.println("weekOfYear \t: " + weekOfYear);
System.out.println("weekOfMonth \t: " + weekOfMonth);
System.out.println("hour \t\t: " + hour);
System.out.println("hourOfDay \t: " + hourOfDay);
System.out.println("minute \t\t: " + minute);
System.out.println("second \t\t: " + second);
System.out.println("millisecond \t: " + millisecond);
Output
2013 Feb 28 13:24:56
year : 2013
month : 1
dayOfMonth : 28
dayOfWeek : 5
weekOfYear : 9
weekOfMonth : 5
hour : 1
hourOfDay : 13
minute : 24
second : 56
millisecond : 0
Example 2.3 – Set a date manually.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,1,28,13,24,56);
System.out.println("#1. " + sdf.format(calendar.getTime()));
//update a date
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.MINUTE, 33);
System.out.println("#2. " + sdf.format(calendar.getTime()));
Output
#1. 2013 Feb 28 13:24:56
#2. 2014 Dec 28 13:33:56
Example 2.4– Add or subtract from a date.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd");
Calendar calendar = new GregorianCalendar(2013,10,28);
System.out.println("Date : " + sdf.format(calendar.getTime()));
//add one month
calendar.add(Calendar.MONTH, 1);
System.out.println("Date : " + sdf.format(calendar.getTime()));
//subtract 10 days
calendar.add(Calendar.DAY_OF_MONTH, -10);
System.out.println("Date : " + sdf.format(calendar.getTime()));
Output
Date : 2013 Nov 28
Date : 2013 Dec 28
Date : 2013 Dec 18
Example 2.5– Convert Date to Calendar.
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "22-01-2015 10:20:56";
Date date = sdf.parse(dateInString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
--------------------------------
import java.text.SimpleDateFormat; import java.util.Calendar; // Make a new Date object. It will be initialized to the current time. SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Calendar calendar = new GregorianCalendar(); calendar.add(Calendar.MONTH, 1); startDate=sdf.format(calendar.getTime()); return startDate;--------------------------------
import java.text.SimpleDateFormat;
import java.util.Calendar;
// Make a new Date object. It will be initialized to the current time.
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.MONTH, 1);
startDate=sdf.format(calendar.getTime());
return startDate;
Комментариев нет:
Отправить комментарий