Go JAVA Calendar Detailed

Source: Internet
Author: User
Tags dateformat time and date

Source: http://blog.csdn.net/zerogotosum/article/details/1671314

What exactly is a Calendar? Chinese translation is the calendar, then we can immediately think of our lives in the Yang (male) calendar, Yin (agricultural) calendar of the points. What is the difference between them?

For example, there are:
The definition of the month-Yang ' (male) calendar 12 months a year, the number of days each month is different; Yin (agriculture) calendar, fixed 28 days per month
The first day of the week-yang (public) calendar Sunday is the first day; Yin (agriculture) calendar, Monday is the first day

In fact, there are many eras in the history of the method. Their differences are too big, for example, a person's birthday is "August 8" so one may be the Yang (male) Calendar of August 8, but also can be the date of the Yin (agriculture) calendar. Therefore, in order to unify the timing, it is necessary to specify a calendar selection. Now the most popular and universal calendar is "Gregorian calendar". That is, we often use "A.D. several years" in the year of narration. The calendar abstract class defines enough methods to allow us to express the rules of a calendar. Java itself provides the implementation of the "Gregorian Calendar" rule. The example we get from calendar.getinstance () is a "Greogriancalendar" object (consistent with the results you get through 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 ();
if (Calendar instanceof GregorianCalendar)
System.out.println ("It's an instance of GregorianCalendar" t;
}
}

The Calendar is an abstract class in Java, and GregorianCalendar is a concrete implementation of it.

We can also implement the class for our own calendar and then return it as a Calendar object (object-oriented feature). On IBM Alphaworks, IBM developers implemented a variety of calendars (http://www.alphaworks.ibm.com/tech/calendars). Also on the Internet, there is the implementation of the Chinese lunar calendar. This article on how to extend the calendar is not discussed, you can see the above calendar of the source to learn.

The conversion of Calendar to Date is simple:

Calendar calendar = Calendar.getinstance ();
Gets the Date object from a Calendar object
Date date = Calendar.gettime ();
The Date object is reflected in a Calendar object,
Calendar/gregoriancalendar no constructor can accept a Date object
So we need to get an instance first and then set the Date object
Calendar.settime (date);


There are some notable things to note when using the Calendar object:

1. Calendar's set () method

Set (int field, int value)-is used to set "year/month/day/hour/minute/second/microsecond" equivalent

field is defined in the Calendar

Set (int year, Int. month, int day, int hour, int minute, int second) but not

Set (int year, Int. month, int day, int hour, int minute, int second, int millisecond) the preceding set (Int,int,int,int,int,int) method does not self- The millisecond is cleared to 0.

In addition, the starting value for the month is 0 instead of 1, so to set the August, we use 7 instead of 8.

Calendar.set (Calendar.month, 7);

We usually need to clear it to 0 in the program logic, otherwise the following situation 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" t);
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 the Calendar to a 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" t);
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" t;
Else
System.out.println ("notequal" t;
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" t;
Else
System.out.println ("notequal" t;
SYSTEM.OUT.PRINTLN ("Processed old Calendar" +cal2.gettime (). GetTime ());
SYSTEM.OUT.PRINTLN ("Processed New Calendar" +cal1.gettime (). GetTime ());
}
}

And then fetch it back in another program (simulating the storage of the database), but the result of the execution is:

NotEqual
Old Calendar 965113200422 <------------The last three-bit millisecond is related to the current time
New Calendar 965113200059 <-----------/
Equals
Processed Old calendar 965113200000
Processed New Calendar 965113200000


Another thing to note is that the Calendar takes a lazy approach to the set () method for performance reasons. The following example is shown in JavaDoc to illustrate this problem:

Calendar Cal1 = Calendar.getinstance ();
Cal1.set (2000, 7, 31, 0, 0, 0); 2000-8-31
Cal1.set (Calendar.month, Calendar.september); It's supposed to be 2000-9-31, 2000-10-1.
Cal1.set (Calendar.day_of_month, 30); If the Calendar is converted to 2000-10-1, then the result should be 2000-10-30
System.out.println (Cal1.gettime ()); The output is 2000-9-30, indicating that the Calendar is not immediately refreshed with its internal records

In the Calendar method, get () and add () will let the calendar refresh immediately. This feature of Set () brings some unexpected results to our development. We'll see the problem later.

2. The tolerance of Calendar objects, lenient settings
We know that a particular month has a different date, and when a user gives the wrong date, how does the Calendar handle it?

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 ());
}
}

The result of its execution is:

Tue Feb 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 the Calendar to lenient false, it will check for incorrect assignments based on a specific month.

3. Unstable Calendar

We know that the Calendar can be serialize, but we have to pay attention to the following questions

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" t);
Out.writeobject (CAL1);
Out.close ();
ObjectInputStream in =
New ObjectInputStream (
New FileInputStream ("Newcalendar.out" t);
Calendar Cal2 = (Calendar) in.readobject ();
Cal2.set (Calendar.millisecond, 0);
System.out.println (Cal2.gettime ());
}
}

The result of the operation is: Thu Jan 00:00:00 PST 1970

It was restored to the starting point of the EPOC, and we said that the Calendar was in an unstable state. The root cause of this problem is that Java does not hold all the information in Serialize GregorianCalendar, so when it is restored to memory and lacks enough information, the Calendar is restored to the EPOCH's starting value. The Calendar object consists of two parts: a field and a microsecond time difference relative to EPOC. The field information is calculated from the microsecond time difference, and the set () method does not force the Calendar to recalculate the field. The value of this field is not correct.

The following code solves 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" t);
Out.writeobject (CAL1);
Out.close ();
ObjectInputStream in =
New ObjectInputStream (
New FileInputStream ("Newcalendar.out" t);
Calendar Cal2 = (Calendar) in.readobject ();
Cal2.get (Calendar.millisecond); Call Get () first to force Calendar refresh
Cal2.set (Calendar.millisecond, 0);//Reset value
System.out.println (Cal2.gettime ());
}
}

The result of the operation is: Tue 00:00:00 PDT 2000

This problem is mainly affected by the inclusion of the Calendar in the Parameter object in EJB programming. After the serialize/deserialize, the direct operation of the Calendar will create an unstable situation.

4. The difference between add () and Roll ()

The Add () feature is very powerful, and add can calculate the fields for the Calendar. If you need to subtract a value, use a negative value, such as Add (field,-value).

Add () has two rules:

When the field being modified exceeds the range it can be, the field larger than it is automatically corrected. Such as:
Calendar Cal1 = Calendar.getinstance ();
Cal1.set (2000, 7, 31, 0, 0, 0); 2000-8-31
Cal1.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 a field smaller than it is immutable (as determined by the implementation class of the Calendar), the small segment will be corrected to the value with the smallest change.

In the example above, 9-31 becomes 9-30, because the change is minimal.

There is only one rule for roll ():
When the modified field exceeds its possible range, then the field larger than it is not corrected. 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, 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 fix the month field.

Introduction to the Date class

Data and Calendar classes:
First, create a Date object R

Let's take a look at a system that uses the current date and time to create a Date object and return a long integer to the simple
Single example. This time is often referred to as the system time of 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 ());
}
}

In Saturday, September 29, 2001, the afternoon is about 6:50, the above example on the system output device
The result shown is 1001803809710. In this case, it is important to note that we used the date construct
The function creates a Date object that does not accept any arguments. And this constructor is internally
The System.currenttimemillis () method is used to obtain the date from the system. If you use

System.out.println (New Date ());

The output form is: Tue 14:28:07 CST 2005

Well, now we know how to get the number of milliseconds that have been going on since January 1, 1970. US as
How can I display this date in a user-aware format? Here the class Java.text.
SimpleDateFormat and its abstract base class Java.text.DateFormat will be useful.

II. custom format for date data

If we want to customize the format of date data, for example Saturday-September-29th-2001. The following example shows
Shows how to accomplish 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 the format string "eee-mmmm-dd-yyyy" is passed to the SimpleDateFormat constructor,
We'll be able to specify the format we want. You should be able to see the ASCII characters in the format string
Tells the format function which part of the date data is displayed below. 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. Passing "Ee-mm-dd-yy" displays
Sat-09-29-01. Please see Sun's Web site for full instructions on getting the date formatting options.

Iii. parsing text data into date objects R

Suppose we have a text string that contains a formatted date object, and we want to parse the
String and creates a date object from the text date data. We will again format the string
"MM-DD-YYYY" calls the SimpleDateFormat class, but this time, we use format parsing instead of
is to generate a text date data. Our example, shown below, will parse the text string
"9-29-2001" and creates a Date object with a value of 001736000000.

Example program:

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 parsed.
String datestringtoparse = "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 (Datestringtoparse);

Now send the parsed date as a Long value
to the system output.
System.out.println (Date.gettime ());
}
catch (Exception ex) {
System.out.println (Ex.getmessage ());
}
}
}

V. Using the standard date formatting process

Now that we can generate and parse custom date formats, let's take a look at how to use the built-in
The formatting process. Method Dateformat.getdatetimeinstance () allows us to use several different
method to get the standard date formatting process. In the following example, we get four built-in date lattices
The process of processing. They include a short, medium, long, and full 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 that we have passed two values in each call to Getdatetimeinstance. First parameter
is a date style, and the second parameter is the time style. They are all basic data type int (integer type). Consider
To readability, we used the constants provided by the DateFormat class: Short, MEDIUM, LONG, and
Full. To know more methods and options for getting the time and date formatting process, see the Sun Company web
Explanation on the site.

When running our example program, it will output the following content to the standard output device:
9/29/01 8:44 PM
SEP, 2001 8:44:45 PM
September, 2001 8:44:45 PM EDT
Saturday, September, 2001 8:44:45 PM EDT

Go JAVA Calendar Detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.