Date Time of Ming Haizang Collection 1.0
-------- It is not original, it is a thought
Java language Calendar, Gregoriancalendar, Date (date), and DateFormat form a basic but very important part of the Java standard. Date is a key part of business logic. All developers should Ability to calculate future dates, custom dates, and analyze text data into date objects. Learning date, date format, date analysis and date calculation.
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 of its specific subclasses, 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.
Java.util.date and its formatting
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,
1
month
On the 1st 00:00:00, you will experience the number of milliseconds after this moment.
1.1. Create java.util.date
Java statistics from
1970
January
1st day
The number of milliseconds represents the date. That is, for example,
1970
January
2nd
It is
January
1st day
The post-86,400,000 ms. same,
1969
December
31st
Be in
1970
January
1st day
The first 86,400,000 ms. Java's Date class uses the long type record these milliseconds. Because long is a symbol integer, the date can be
1970
January
1st day
Before, you can also follow this. The maximum positive value and maximum negative value indicated by long types can be easily representative of 290,000,000, which is suitable for most people's time requirements.
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 ();
// Print the specific year, month, day, hour, minute, second to timely district
System.out.println (Date.getTime ());
}
}
on Saturday,
2001
Year 9
Month 29
day
About 6:50 in the afternoon, the above example shows the result of the system output device is 1001803809710. In this example, it is worth noting that we use the Date constructor to create a date object, this constructor is not accepted Parameters. This constructor uses the System.CurrentTimeMillis () method internally to get the date from the system.
// 1 year ago
Java.util.date mydate = new java.util.date ();
Long myTime = (mydate.gettime () / 1000) -60 * 60 * 24 * 365;
MyDate.settime (MyTime * 1000); string mdate = formatter.format (mydate);
// Tomorrow
mydate = new java.util.date ();
MyTime = (mydate.gettime () / 1000) 60 * 60 * 24;
mydate.settime (MyTime * 1000);
MDATE = formatter.format (mydate);
// The number of days between two times
SimpleDateFormat MyFormatter = New SimpleDateFormat ("YYYY-MM-DD");
Java.util.date date = myformatter.parse ("
2003-05-1
");
Java.util.date mydate = myformatter.parse ("
1899-12-30
");
Long day = (Date.getTime () - mydate.gettime ()) / (24 * 60 * 60 * 1000);
// Half an hour
SimpleDateFormat Format = New SimpleDateFormat ("YYYY-MM-DD HH: MM: SS");
Java.util.date Date1 = format.parse ("2002-02-28 23:16:00);
Long Time = (Date1.gettime () / 1000) 60 * 30;
Date1.settime (Time * 1000);
String mydate1 = formatter.format (date1);
// Annual monthly review date
SimpleDateFormat Formatter2 = New SimpleDateFormat ("YYYY-MM F E");
Java.util.date Date2 = formatter2.parse ("2003-05 5 Friday");
SimpleDateFormat Formatter3 = New SimpleDateFormat ("YYYY-MM-DD");
String mydate2 = formatter3.Format (date2);
// Seeking a week
mydate = myformatter.parse ("
2001-1-1
");
SimpleDateFormat Formatter4 = New SimpleDateFormat ("E");
String mydate3 = formatter4.format (mydate);
1.2. Date format
Can you display this date in a format that understands the user? Here class java.text.SIMPLEDATEFORMAT and its abstract base class java.text.dateFormat. So, now we already know how to get it from
1970
January
1st day
The number of millisecots that started to experience. How do we forms format?
/ / We can use the following code components 2001/8/8 8: 8
Import java.io. *;
Import java.util. *;
Public class whatisdate
{
Public static void main (String [] args) {
Date Date = New Date (2001, 8, 8, 8, 8, 8);
System.out.println (date);
}
}
Java's compiler actually reports the following information (Sun JDK1.3, Windows 2000)
note:
WhatSdate.java uses or covers an API that does not encourage use. note:
Re-compile them with -DepRecation to get details. !
So what is the DATE object to meet which needs? It seems that it is not used to implement the year / month / day hour: minutes of the minute. We look at the Java documentation, we see a getTime () method, it is turned back to a long value.
The document further tells us that this value represents the current system time
1970/1/1 0: 0
The millisecond difference, and is under the GMT time zone (also known as EPOC). If we specify the time before this, it will return a negative value.
This discovery allows us to have a new understanding of the Date object - Date stored with the deviation value of EPOC. In other words, we can also express time through the long type? Yes, this guess is to get Java support:
// Second method of obtaining a current time
Long dateinmilliseconds = system.currenttimemillis ();
// At this time, it is just a string of numbers.
System.out.println (DateinmilliseConds);
Programmers for program execution efficiency can find that this method only generates a Java's original type (Primitive Type ", no need to instantiate an object. So if we are processed by time, you can use long to replace DATE objects.
The most typical application is to obtain the current time of the system at a period of start and end, and then calculate the time required for code execution (microose level).
Long Start = system.currenttimemillis ();
// code segment
System.out.println ("Need" (System.currentTimeMillis () - START) "Microsecond");
Then when we want to display this long value, we can use it to construct a Date object:
Date Date = New Date (DateinmilliseConds);
System.out.println (date);
We have seen the most basic representation of time in Java, with the deviation value of EPOC. The DATE object is a package for one of its objects. We also see it at the same time, in the current world, our description is usually defined by "a certain day of a certain day" in a certain year. Date's display (actually the toString () method) describes this information, but Java does not recommend that we use this way directly to the component Date object. So we need to find which object can achieve this demand. This is the function of the Calendar object we have to tell below.
Before we study Calendar, remember that Date is just an object package to the long value (based on GMT time zone). The year / month / yard of it exhibits the time of minutes, the time of the minute area is just provided by its toString () method. Don't confuse this illusion.
If we want to customize the format of the date data, for example, Saturday - September - 29 - 2001. The following example shows how to complete this work:
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 is 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 full instruction of the Sun's Web Site Get Date Format Option.
1.3. Text Data Analysis 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 rather than generating a text date data. Our example, displayed below, will resolve text strings
9-29-2001
"And create a date object having a value of 001736000000.
With the PARSE () method, DateFormat can create a Date object in a string. This method can throw Parsexception, so you must use the appropriate exception handling technology.
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 DateStringToparse = "
9-29-2001
"
Try {
// Parse The text Version of the date.
// we have to perform the paramedion in a
// try-catch construct in case dateStringtopival
// does not contain a date in the format we are evting.
Date Date = BartdateFormat.Parse (dateStringTopival);
// now send the pased date as a long value
// to the system output.
System.out.println (Date.getTime ());
} catch (exception ex) {
System.out.println (ex.getMessage ());
}
}
}
1.4. Using 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 got four built-in date formatting procedures. 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 DateFormat class to provide constants: short, medium, long, and full. To know more methods and options for getting time and date formatting procedures, see the interpretation on Sun Web site. Run our When the example is, 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
2. Calendar calendar
First, please remember that Calendar is just an abstract class, that is, you can't get an instance of it directly. In other words, you can provide a Calendar object you develop.
What exactly is a Calendar? Chinese translation is the calendar, then we can immediately think of our lives in our lives (public) calendar, yin (agricultural) calendar. Where is their difference?
For example:
The definition of the month - Yangu (public) 12 months, each month is different; Yin (agriculture) calendar, 28 days per month, weekly first day - Yang (public) calendar Is the first day; Yin (agriculture) calendar, Monday is the first day
In fact, there are many ways to have many episodes in history. Their differences are too big, such as a person's birthday is "
August 8
"Then one may be Yang (public) calendar
August 8
But it can also be the date of the Yin (agricultural) calendar. So for the unity of timing, you must specify a calendar selection. The most popular and universal calendar now is "Gregorian Calendar". That is, we often use the "AD a few years" during the year. The Calendar abstract class defines enough ways to express the rules of the calendar. Java itself provides an implementation of the "Gregorian Calendar" rule. Our instances obtained from Calendar.getInstance () are a "Greogriancalendar" object (consistent with the results obtained by New GregorianCalendar ()). The following code can prove this:
Import java.io. *;
Import java.util. *;
Public Class Whatiscalendar
{
Public static void main (String [] args) {
Calendar Calendar = Calendar.getInstance ();
Calendar InstanceOf Gregoriancalendar
System.out.println ("IT IS An Instance of Gregoriancalendar);
}
}
Calendar is an abstract class in Java (Abstract Class), and GregorianCalendar is a specific implementation thereof.
The conversion of Calendar and Date is very simple:
Calendar Calendar = Calendar.getInstance ();
// Get a Date object from a Calendar object
Date Date = Calendar.gettime ();
// React up the Date object into a Calendar object,
// Calendar / Gregoriancalendar does not have a constructor to accept DATE objects
// So we must first get an instance, then set the Date object
Calendar.SetTime (date);
When the Calendar object is in use, there are some worthless things:
Calendar's set () method
Set (int field, int value) - is used to set the "year / month / day / hour / minute / sec / microsecond"
Field definition in Calendar
Set (int year, int month, int standard), but no set (int year, int month, int custom, int hour, int minute, int special, int millisecond) set (int, The INT, INT, INT, INT, INT) method will not automatically clear the millisecond.
In addition, the starting value of the month is 0 instead of 1, so we use 7 instead of 8 when we set up August.
Calendar.Set (Calendar.Month, 7);
We usually need to clear it into 0 in the program logic, otherwise the following may occur:
Import java.io. *;
Import java.util. *;
Public Class Whatiscalendarwrite
{
Public static void main (string [] args) throws exception {
ObjectOutputStream out =
New ObjectOutputStream
New FileOutputStream ("Calendar.out")); Calendar Cal1 = Calendar.GetInstance ();
Cal1.set (2000, 7, 1, 0, 0, 0);
Out.writeObject (CAL1);
Calendar Cal2 = Calendar.getInstance ();
Cal2.set (2000, 7, 1, 0, 0, 0);
Cal2.set (Calendar.Millisecond, 0);
Out.writeObject (CAL2);
Out.close ();
}
}
We save Calendar to the file
Import java.io. *;
Import java.util. *;
Public Class WhatiscalendarRead
{
Public static void main (string [] args) throws exception {
ObjectInputStream in =
New ObjectInputStream
New fileInputstream ("calendar.out"));
Calendar Cal2 = (Calendar) in.readObject ();
Calendar Cal1 = Calendar.getInstance ();
Cal1.set (2000, 7, 1, 0, 0, 0);
IF (Cal1.Equals (CAL2))
System.out.println ("Equals");
Else
System.out.println ("Notequal");
System.out.println ("Old Calendar" Cal2.getTime (). Gettime ());
System.out.println ("New Calendar" Cal1.getTime (). GetTime ());
Cal1.set (Calendar.MilliseCond, 0);
Cal2 = (Calendar) in.readObject ();
IF (Cal1.Equals (CAL2))
System.out.println ("Equals");
Else
System.out.println ("Notequal");
System.out.println ("Processed Old Calendar" Cal2.gettime (). GetTime ());
System.out.println ("Processed New Calendar" Cal1.getTime (). Gettime ());
}
}
Then take another program again (simulate the storage of the database), but the result of the execution is:
Notequal
Old Calendar 965113200422 <------------ The last three MilliseCond is related to the current time
New Calendar 965113200059 <----------- /
Equals
Processed Old Calendar 965113200000
Processed New Calendar 965113200000
In addition, what we have to pay attention to is that Calendar takes a method of delaying the calculation of the set () method for performance reasons. There is an example in javadoc to explain this problem:
Calendar Cal1 = Calendar.getInstance ();
Cal1.set (2000, 7, 31, 0, 0, 0); //
2000-8-31cal1.set (Calendar.Month, Calendar.september); / / should be 2000-9-31, that is
2000-10-1
Cal1.set (Calendar.day_of_month, 30); // If Calendar is transformed into
2000-10-1
So now the result is
2000-10-30
System.out.println (Cal1.getTime ()); // Output is
2000-9-30
Description Calendar is not immediately refreshed with its internal record
In Calendar's approach, GET () and add () will let Calendar refreshed immediately. This feature of Set () will bring us unexpected results. We will see this problem later.
2. Calendar's fault tolerance, Lenient settings
We know that there is a different date of the specific month. How do Calendar deal with Calendar when a user gives an error date?
Import java.io. *;
Import java.util. *;
Public Class Whatiscalendar
{
Public static void main (string [] args) throws exception {
Calendar Cal1 = Calendar.getInstance ();
Cal1.set (2000, 1, 32, 0, 0, 0);
System.out.println (Cal1.getTime ());
Cal1.setlenient (FALSE);
Cal1.set (2000, 1, 32, 0, 0, 0);
System.out.println (Cal1.getTime ());
}
}
Its execution result is:
Tue Feb 01 00:00:00 PST 2000
Exception in thread "main" java.lang.illegalargumentException
At java.util.gregoriancalendar.computetime (Gregoriancalendar.java: 1368)
At java.util.calendar.Updatetime (Calendar.java:1508)
At java.util.calendar.gettimeinmillis (calendar.java:890)
AT java.util.calendar.gettime (Calendar.java: 871)
At whatiscalendar.main (whatiscalendar.java: 12)
When we set this Calendar as Lenient False, it checks the error assignment based on a specific month.
3. Unstable Calendar
We know that Calendar can be SERIALIZE, but we must pay attention to the following problems.
Import java.io. *;
Import java.util. *;
Public Class Unstablecalendar IMPLEments Serializable
{
Public static void main (string [] args) throws exception {
Calendar Cal1 = Calendar.getInstance ();
Cal1.set (2000, 7, 1, 0, 0, 0);
Cal1.set (Calendar.MilliseCond, 0);
ObjectOutputStream out =
New ObjectOutputStream
New FileOutputStream ("Newcalendar.out"));
Out.writeObject (CAL1); out.close ();
ObjectInputStream in =
New ObjectInputStream
New FileInputStream ("Newcalendar.out")));
Calendar Cal2 = (Calendar) in.readObject ();
Cal2.set (Calendar.Millisecond, 0);
System.out.println (Cal2.getTime ());
}
}
The result of running is: Thu Jan 01 00:00:00 PST 1970
It is restored to the starting point of EPOC, saying that this Calendar is in an unstable state. The root cause of this problem is that Java has not saved all information when Serialize Gregoriancalendar, so when it is restored to memory, Calendar will be restored to the starting value of EPOCH. The Calendar object consists of two parts: field and microsecond times relative to EPOC. Field information is calculated by microsecond time difference, and the set () method does not force the Calendar to recalculate the field. This is not right in the field value.
The following code can solve this problem:
Import java.io. *;
Import java.util. *;
Public Class Stablecalendar IMPLEMENTS SERIALIZABLE
{
Public static void main (string [] args) throws exception {
Calendar Cal1 = Calendar.getInstance ();
Cal1.set (2000, 7, 1, 0, 0, 0);
Cal1.set (Calendar.MilliseCond, 0);
ObjectOutputStream out =
New ObjectOutputStream
New FileOutputStream ("Newcalendar.out"));
Out.writeObject (CAL1);
Out.close ();
ObjectInputStream in =
New ObjectInputStream
New FileInputStream ("Newcalendar.out")));
Calendar Cal2 = (Calendar) in.readObject ();
Cal2.get (Calendar.MilliseCond); // Toned GET (), forced Calendar Refresh
Cal2.set (Calendar.MilliseCond, 0); // Re-set value
System.out.println (Cal2.getTime ());
}
}
The result of the run is: Tue Aug 01 00:00:00 PDT 2000, this problem mainly affects when EJB programming, the parameter object contains Calendar. After serialize / deserialize, direct operation Calendar will generate unstable situations.
4. ADD () difference between with roll ()
Add () features very powerful, ADD can calculate the field of Calendar. If you need to subtract the value, you can use the negative value, such as add (field, -value).
ADD () has two rules:
When the modified field exceeds it can, it is automatically corrected than its large field. Such as:
Calendar Cal1 = Calendar.getInstance ();
Cal1.set (2000, 7, 31, 0, 0, 0); //
2000-8-31cal1.add (Calendar.month, 1); // 2000-9-31 =>
2000-10-1
,right? System.out.println (CAL1.Gettime ()); / / The result is
2000-9-30
Another rule is that if it is unstrenomable than its small field (determined by Calendar), then the small field will fix the smallest value.
With the above example, 9-31 will become 9-30 because the change is minimal.
Rule of Roll () has only one: When the modified field exceeds it can, it is not corrected than its large field. Such as:
Calendar Cal1 = Calendar.getInstance ();
Cal1.set (1999, 5, 6, 0, 0, 0); //
1999-6-6
Sunday
Cal1.roll (Calendar.Week_OF_MONTH, -1); //
1999-6-1
, on Tuesday
Cal1.set (1999, 5, 6, 0, 0, 0); //
1999-6-6
Sunday
Cal1.add (Calendar.Week_Of_Month, -1); //
1999-5-30
Sunday
WEEK_OF_MONTH is smaller than the Month field, so ROLL cannot correct the Month field.
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 10th Friday below.
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 ot calendar
// 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 ypriday by adding 7 days. Cal.Add (Gregoriancalendar.day_of_month, 7); // if The day of month is 13 We Have
// annother friday the 13th.
IF (Cal.get (Gregoriancalendar.day_of_month) == 13) {
Friday13counter ; system.out.println (DateFormat.Format (Cal.getTime ()));
}
}
}
}
In this example we made interesting functions:
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.
The output of our 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, February 13, 2004
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
The Calendar class is the concept of variable domain. Each class element is domain, and these domains behave in the Calendar class as static variables. These variable domains can be obtained or set by the Get / Set class method.
// Get the default Calendar instance, set the time Calendarcal = Calendar.GetInstance (); intYear = CAL.GET (Calendar.Year); Cal.Set (Calendar.Month, Calendar.november); Calendar class Add and Roll Methods The ability to convert between the dates. Each method is modified by a parameter variable and a parameter value, and it can be modified by this parameter value of positive or negative numbers. It is only that the add method can overflow to the high order variable domain. For example, if you leave three days from September 3, you will get:
Calendar Cal = Calendar.getInstance ();
Cal.Add (Calendar.date, -3);
// value: Saturday August 31 23:43:19 Edt 2002
However, use the Roll method to roll back to three days:
Calendar Cal = Calendar.getInstance ();
Cal.roll (Calendar.date, -3);
// value: Monday, September 30, 23:43:47 EDT 2002 This is why it usually uses the reasons for the ADD method.
There is also a functional method hidden in the subclass of the most common Calendar - theILAPYEAR (determining whether it is a leap year) method.
Calendar Cal = Calendar.getInstance ();
BooleanleApyear = (Gregoriancalendar) Cal) .IsLeapyear (2002); // This value is false
Although it is an example method, the behavior of the IsleApyear method is like a static method, and the parameter pass value of the year is required to give the calendar.
In fact, a few months ago, a few months ago, should be better (than Date) with Calendar class.
Calendar Cal = Calendar.getInstance ();
Cal.SetTime (date);
Cal.Add (Calendar.Month, 1);
Cal.Add (Calendar.Year, 2000);
Date = ca.gettime ();
The Java.util.Calendar class seems to be a complex version of the Data class by the function modified by the takeover date. But it also provides additional features, not to mention its international support, making it worth having difficulty curves.
3. Using the Gregoriancalendar class
Create a way to represent any date using the GregorianCalendar class constructor, which is included in the java.util package:
Gregoriancalendar (int year, int month, int Date)
Talents said that in January is 0, February is 1, and it is pushed by this class, which is 11. Because most people are accustomed to using words rather than using numbers, this program may be more easy to read, parent Calendar uses constants to represent months: January, February, and more. So, create the date of manufacturing the first power plane (December 17, 1903), you can use:
Gregoriancalendar firstflight = New Gregoriancalendar (1903, Calendar.December, 17);
For clear considerations, you should use the previous form. However, you should also learn how to read the short format below. The following example also indicates that DECEMBER 17, 1903 (remember, in the short format, 11 means a decEmber)
Gregoriancalendar firstflight = New Gregoriancalendar (1903, 11, 17); In the previous section, you learned to convert the Date object to the string. Here you can do the same thing; but first, you need to convert the GregorianCalendar object to Date. To do this, you can use the getTime () method to inherit from its parent Calendar. The getTime () method returns the corresponding DATE object of GregorianCalendar. You can create a GregorianCalendar object, convert to the DATE object, get and output a process such as the corresponding string. Here is an example:
Import java.util. *;
Import java.text. *;
PUBLIC CLASS FLIGHT {
Public static void main (String [] args) {
Gregoriancalendar firstflight = New Gregoriancalendar (1903, Calendar.December, 17);
Date d = firstflight.gettime ();
DateFormat DF = DateFormat.getdateInstance ();
String s = df.format (d); System.out.Println ("First Flight WAS" S);
}
Sometimes it is useful to create an instance of the GregorianCalendar class representing the current time. You can simply use the GregorianCalendar constructor without parameters, like this:
Gregoriancalendar thisday = new gregoriancalendar ();
An example of an exemplary output today, using the Gregoriancalendar object:
Import java.util. *;
Import java.text. *;
Class Today {
Public static void main (String [] args) {
Gregoriancalendar thisday = new gregoriancalendar ();
Date d = thisday.gettime ();
DateFormat DF = DateFormat.getdateInstance ();
String s = DF.FORMAT (D);
System.out.println ("Today IS" S);
}
}
Note that the DATE () constructor and the GregorianCalendar () constructor are very similar: all objects are created, and the conditions are simple, representing today.
The GregorianCalendar class provides a method of processing a date. A useful method is add (). Using the add () method, you can increase the year, the number, the number of days to the date object. To use the add () method, you must provide the quantity to increase to increase. Some useful fields are DATE, MONTH, YEAR, and WEEK_OF_YEAR. The following program uses the add () method to calculate a date in the next 80 days. In Jules
In 1872
October
2nd
The date after 80 days:
Import java.util. *;
Import java.text. *;
Public class world {
Public static void main (String [] args) {
Gregoriancalendar Worldtour = New Gregoriancalendar (1872, Calendar.October, 2);
Worldtour.add (Gregoriancalendar.date, 80);
Date d = worldtour.gettime ();
DateFormat DF = DateFormat.getdateInstance ();
String s = DF.FORMAT (D);
System.out.println ("80 Day Trip Will End" S);
}
}
ADD () an important side effect is that it changed the original date. Sometimes it is important to have the original date and the revised date. Unfortunately, you can't create a GregorianCalendar object, set it and the original equivalent (Equal). The reason is that two variables point to the same Date () object address. If the DATE object changes, the two variables point to the changed date object. Instead of this approach, you should create a new object. The following program demonstrates this approach: Import java.util. *;
Import java.text. *;
Public class threedates {
Public static void main (string [] args) {Gregoriancalendar GC1 = New Gregoriancalendar (2000, Calendar.January, 1);
Gregoriancalendar GC2 = GC1;
Gregoriancalendar GC3 = New Gregoriancalendar (2000, Calendar.january, 1); // Three Dates All Equal to January 1, 2000
GC1.Add (Calendar.Year, 1);
// GC1 and GC2 Are Changed
DateFormat DF = DateFormat.getdateInstance ();
Date D1 = gc1.gettime ();
Date D2 = gc2.gettime ();
Date D3 = gc3.gettime ();
String S1 = DF.FORMAT (D1);
String S2 = DF.FORMAT (D2);
String S3 = DF.FORMAT (D3);
System.out.Println ("GC1 IS" S1);
System.out.println ("GC2 IS" S2);
System.out.Println ("GC3 IS" S3);
}
}
After the program is running, GC1 and GC2 are turned into 2001 (because the two objects point to the same date, and Date has changed). The object GC3 points to a separate date, it is not changed.
Package com.minght.sys.util;
/ ** *
Title: Open source, open P> *
Description: Opeansource P> *
Copyright: CopyRight (c) 2004 p> *
Company: 眀海 p> * @Author Haitang Ming * @version 1.0 * /
Import java.util. *; import java.math.bigDecimal; import java.math.biginteger; import java.sql.timestamp; import java.text. *;
Public class timeutil {
/ ** * Translate the Date type to string type "Arbitrary" format * java.sql.date, java.sql.timestamp type is a subclass of java.util.date type * @Param Date Date * @Param Format string * "2003-01-01" Format * "YYYY YOR MY D Japanese *" YYYY-MM-DD HH: MM: SS "format * @return string * / public static string DateTostring (java.util.date date, string Format) {
IF (date == null || format == null) {Return NULL;}
SimpleDateFormat SDF = New SimpleDateFormat (Format); string str = sdf.format (date); return str;} / ** * Translate String Type Date to Java.utl.date Type "2003-01-01" format * @Param String To format string * @Param Format string * @return date * / public static java.util.date stringtoutildate (string str, string format) {
IF (str == null || format == null) {return null;}
SimpleDateFormat SDF = New SimpleDateFormat (Format);
Java.util.date date = null; try {date = SDF.PARSE (STR);} catCH (Exception E) {} Return Date;}
/ ** * Translate the String Type Date into java.sql.date type "2003-01-01" format * @Param string * @Param Format string * @return Date * / public static java.sql.date stringtosqldate (String Str, string format) {
IF (str == null || format == null) {return null;}
SimpleDateFormat SDF = New SimpleDateFormat (Format);
Java.util.date date = null; try {date = sdf.parse (STR);} catch (Exception E) {return null;} return new java.sql.date (Date.getTime ());}
/ ** * Translate String Type Dates into Java.sql.date Type "2003-01-01" Format * @Param String * @Param Format String * @Return TimeStamp * / Public Static Java.sql.TimeStamp StringTotimeStamp (String Str, string format) {
IF (str == null || format == null) {return null;}
SimpleDateFormat SDF = New SimpleDateFormat (Format);
Java.util.date date = null; try {date = sdf.parse (STR);} Catch (Exception E) {return null;} return new java.sql.timestamp (Date.getTime ());} / ** * Translate the java.util.date date to java.sql.date Type * @Param Date * @return Formatted Java.Sql.date * / public static java.sql.date Tosqldate (Date Date) {
IF (Date == Null) {Return Null;}
Return new java.sql.date (Date.gettime ());} / ** * Transform strings into time format string to string * @Param string * @Param Format string * @return string * / public static string TodateString String str, string newformat {
Return DateTostring (StringToutildate (STR, OLDFORMAT), NewFormat;
}
/ ** * Transform calendar into date * @Param Calendar Calendar * @Return Date * / public static java.util.date Convertodate (java.util.calendar Calendar) {Return Calendar.GetInstance (). Gettime ();
/ ** * Translate the date to calendar * @Param Date Date * @return calendar * / public static java.util.calendar communication {Calendar Calendar = Calendar.GetInstance (); Calendar.Settime Date); return calendar;
/ ** * Since the beginning of a day, after a few days a few days a few days a few days, how many days is the date * a few days a few days a few days a few seconds can be negative * @Param Date Date * @Param year int * @Param Month Int * @Param day int * @Param Hour int * @Param min int * @Param sec int * @return date * / public static java.util.date modifydate (java.util.date Date) , int year, int month, int custom, {calendar cal = calendar.getInstance (); Cal.SetTime (date); Cal.Add (Calendar.Year, Year); Cal.Add Calendar.month, Month; Cal.Add (Calendar.date, day); Cal.Add (Calendar. Hour, Hour); Cal.Add (Calendar.minute, Min); Cal.Add (Calendar.Second, SEC Return Cal.getTime ();
}
/ ** * Get the current date time * 1: Year * 2: Month * 3: day * / public static int getCurtime (INT i) {if (i == 1) {Return Java.util.calendar.GetInstance (). Get (Calendar.Year);} else if (i == 2) {Return Java.util.calendar.GetInstance (). get (Calendar.mont) 1;} else if (i == 3) {Return Java. Util.calendar.getInstance (). get (calendar.date);} return 0;
}
Public static void main (string [] args) {system.out.println (calendar.getInstance (). gettime (), - 1, -1, -1, -1, -1, -1), "YYYY-MM-DD HH: mm: SS"));
}
}