http://www.chinaunix.net Author: echoguo Posted: 2004-01-15 12:46:25
The Java language Calendar (Calendar), Date (date), and DateFormat form a basic but very important part of the Java standard. Date is a critical part of business logic. All developers should be able to calculate Future date, custom date display format, and analyze the text data into date objects. We wrote two articles, this is the first, we will probably learn the date, date format, date analysis and date.
We will discuss the following categories:
1, specific class (and abstract class relative) java.util.date 2, abstract class java.text.dateformat and one of its specific subclasses, java.text.SIMPLEDATEFORMAT 3, abstract class java.util.calendar and one Specific subclass, java.util.gregoriancalendar
The specific class can be instantiated, but the abstraction category is not. You must first implement a specific subclass of an abstract class.
The DATE class began evolving from the Java Development Kit (JDK) 1.0, which only contains several ways to obtain or set a date data, such as month, day, and year. These methods are now criticized and have already It was transferred to the Calendar class, and we will discuss it in this article. This improvement is intended to better handle the internationalization of date data. Like the JDK 1.1, the Date class is actually just a parcel class. It contains a long integer data, indicating that from GMT (GMT time) in 1970, January 1 00:00:00, or after the number of milliseconds experienced.
First, create a date object
Let's see a simple example of using the current date and time of the system and return a long integer. This time is often referred to as a system time for the Java Virtual Machine (JVM) host environment. Import java.util.date;
Public class dateexample1 {public static void main (string [] args) {// get the system date / time date date = new date ();
System.out.println (Date.getTime ());}}
On Saturday, September 29, 2001, about 6:50 in the afternoon, the above example is shown on the system output device 1001803809710. In this example, it is worth noting that we use the Date constructor to create a Date objects, this constructor does not accept any parameters. This constructor uses the System.CurrentTimeMillis () method internally to obtain a date from the system.
So, now we already know how to get milliseconds since January 1, 1970. How can we display this date with a format that users understand? Here, Java.Text.SIMPLEDATEFORMAT and it Abstract base class java.text.dateFormat will be derived.
Second, the custom format of date data
If we want to customize the format of the date data, for example, Saturday - September-29-29-2001. The following example shows how to complete this: import java.text.SIMPLEDATEFORMAT; import java.util.date;
Public class dateexample2 {
Public static void main (String [] args) {
SimpleDateFormat BartdateFormat = New SimpleDateFormat ("eeee-mmmm-dd-yyyy);
Date Date = new date ();
System.out.println (BartdateFormat.Format (Date));}}
As long as we pass the format string "EEE-MMMM-DD-YYYY" by the constructor of SimpleDateFormat, we can specify the format you want. You should be able to see, the ASCII character in the format string tells the format function below the date of display Which part of the data. Eeee is the week, MMMM is the month, DD is the day, YYYY is the year. The number of characters determines how the date is formatted. Pass "EE-MM-DD-YY" will display SAT-09 -29-01. Please check the complete instructions for Sun's Web Site Get Date Formatting Options .. Third, parsing text data into date objects
Suppose we have a text string containing a formatted date object, and we want to resolve this string and create a date object from text date data. We will call again to format string "mm-dd-yyyy" SIMPLEDATEFORMAT class, but this time, we use formatted to resolve instead of generating a text date data. Our example, displayed below, will resolve text strings "9-29-2001" and create a value of 001736000000.
Example: import java.text.SIMPLEDATEFORMAT; import java.util.date;
Public class dateexample3 {
Public static void main (string [] args) {// create a date formatter That can parse dates of // the form mm-dd-yyyy. SimpleDateFormat BartdateFormat = New SimpleDateFormat ("mm-dd-yyyy");
// Create a string containing a text date to be pased. String DateStringTopArs = "9-29-2001";
try {// Parse the text version of the date. // We have to perform the parse method in a // try-catch construct in case dateStringToParse // does not contain a date in the format we are expecting. Date date = bartDateFormat .parse (dateStringtopival);
// Now send the pased date as a long value // to the system outprint. System.out.println (Date.getTime ());} catch (exception ex) {system.out.println (ex.getMessage ()) }}}
V. Use of standard date formatting process
Since we can generate and analyze custom date formats, let's take a look at how to use the built-in formatting process. Method DateFormat.getDateTimeInstance () allows us to obtain standard date formatting processes with several different ways In the following example, we have obtained four built-in date formatting processes. They include a short, medium, long, and complete date format. Import java.text.dateFormat; import java.util. Date;
Public class dateexample4 {
Public static void main (string [] args) {date date = new date ();
DateFormat shortdateFormat = DateFormat.GetdateTimeInstance (DateFormat.short, DateFormat.short);
DateFormat MediumdateFormat = DateFormat.getdateTimeInstance (DateFormat.medium, DateFormat.medium); DateFormat LongdateFormat = DateFormat.getDatetimeInstance (DateFormat.long, DateFormat.long);
Dateformat fulldateformat = DateFormat.getdateTimeInstance (DateFormat.full, DateFormat.full);
System.out.println (shortDateFormat.format (date)); System.out.println (mediumDateFormat.format (date)); System.out.println (longDateFormat.format (date)); System.out.println (fullDateFormat. Format (date));}}
Note We pass two values in each call to getDateTimeInstance. The first parameter is a date style, and the second parameter is a time style. They are all basic data type Int (integer). Considering readable Sex, we use the constants provided by the DateFormat class: Short, Medium, Long, and Full. To know more methods and options for getting time and date formatting procedures, see the interpretation of Sun Web Sites.
When running our example, it will output the following to the standard output device: 9/29/01 8:44 PM Sep 29, 2001 8:44:45 Pm September 29, 2001 8:44:45 PM Edt Saturday , September 29, 2001 8:44:45 PM EDT
6. Calendar class
We are now able to format and create a date object, but how can we set and get specific parts of date data, such as hours, days, or minutes? How do we add or subtract values in these parts? • The answer is to use the Calendar class. As mentioned earlier, the method in the Calendar class replaces the method of being saved in the DATE class.
Suppose you want to set, get, and manipulate a date object, more than one month or a week. In order to demonstrate this process, we will use the specific subclava.util.gregoriancalendar. Consider the following Example, it calculates the following 10th Friday is No. 13. Import java.util.gregoriancalendar; import java.util.date; import java.text.dateFormat;
Public class dateexample5 {
Public static void main (string [] args) {dateformat dateformat = DateFormat.GetDateInstance (DateFormat.full);
// Create Our Gregorian Calendar. Gregoriancalendar Cal = New Gregoriancalendar ();
// set the date and time of outten // to the system & s date and time cal.settime (new date ());
System.out.println ("System Date:" DateFormat.Format (Cal.getTime ());
// Set the day of week to FRIDAY cal.set (GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.FRIDAY); System.out.println ( "After Setting Day of Week to Friday:" dateFormat.format (cal.getTime ())) ; int friday13counter = 0; while (Friday13counter <= 10) {
// Go to the next friend, by adding 7 days. Cal.Add (GregorianCalendar.day_of_month, 7);
// if the day of month is 13 we have // another friday the 13th. If (Cal.get (Gregoriancalendar.day_of_month) == 13) {Friday13counter ; System.Out.println (DateFormat.Format () ));}}}}
In this example we made interesting function calls: cal.set (Gregoriancalendar.day_of_week, gregoriancalendar.friday);
And: Cal.Add (Gregoriancalendar.day_of_month, 7);
The SET method allows us to adjust our time to Friday. Note that we use constant day_of_week and y, which uses constants to enhance the readability of the code. Add method allows us to date Adding a value. All complex calculations of the annual years are automatically handled by this method.
Our example of this example is: System Date: Saturday, September 29, 2001 When we set it into Friday, we will become: Friday, September 28, 2001 Friday, September 13, 2002 Friday, December 13, 2002 Friday, June 13, 2003 Friday, August 13, 2004 Friday, May 13, 2005 Friday, January 13, 2006 Friday, October 13, 2006 Friday, April 13, 2007 Friday, July 13, 2007 Friday, June 13, 2008
Seven, time to master in your hand
With these Date and Calendar classes, you should be able to create many methods using java.util.date, java.text.SIMpleDateFormat, and Java.util.gregorianCalendar.
In future articles, we will discuss the use of higher DATE and Calendar classes, including time zone and international format. We will also examine two date classes java.sql.date and java.util.date the difference.