JAVA Calendar Specific Explanation

Source: Internet
Author: User
Tags dateformat

(The date class will be introduced at the end of the article, assuming interest, and can go straight to the last reading)

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 are the differences between them?

For example, there are:
The definition of the month-Yang ' (male) calendar 12 months a year, the number of days each one months are different; Yin (agriculture) calendar, 28 days fixed every one months
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" that 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. The most popular and universal calendar today is "Gregorian calendar". That is, we often use "A.D. several years" when we tell the year. The calendar abstract class defines enough methods so that we can express the rules of the 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 detailed implementation of it.

We can also implement our own calendar class, and then return it as a Calendar object (object-oriented feature). On IBM Alphaworks, IBM's developers have implemented multiple calendars (http://www.alphaworks.ibm.com/tech/calendars). The same on the Internet, there are also the implementation of the Chinese lunar calendar. This article on how to extend the calendar is not discussed, we can look at the above calendar source code to learn.

The Calendar and Date conversions are easy:

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 was voluntarily 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 in 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 operation 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 we should note is that the Calendar takes the set () method for performance reasons to defer the calculation. The following examples are available 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); Assuming the Calendar is converted to 2000-10-1, the result is now 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 () 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 this operation 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 checks for incorrect assignments based on a specific month.

3. Unstable Calendar

We know that the Calendar can be serialize, but we should 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 execution is actually: 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 calculate the field again. The field value is not correct.

The following code can solve the 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 execution is: Tue 00:00:00 PDT 2000

This problem is mainly affected by the inclusion of the Calendar in the reference 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 powerful, and add is able to calculate the fields of the Calendar. Suppose you need to subtract a value, you can use a negative value, such as Add (field,-value).

Add () has two rules:

When the field is changed beyond its scope, then the larger field will be actively modified by itself. 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), then the small segment will be corrected to the value with the smallest change.

In the example above, 9-31 will become 9-30, due to the smallest change.

The rules of Roll () only have one:
A field larger than it will not be corrected when the changed field is beyond its scope. 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 sample 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 example above on the system output device
The result shown is 1001803809710. In this example, it is important to note that we used the date construct
The function creates a Date object that does not accept any of the parameters. And this constructor is internally
The System.currenttimemillis () method is used to obtain the date from the system. Assuming

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 started on January 1, 1970. US as
What ability to display this date in a user-specific 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, such as Saturday-September-29th-2001. The following sample shows
Show how to finish this job:

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

Just by passing the format string "eee-mmmm-dd-yyyy" to the SimpleDateFormat constructor,
We can specify the format we want. You should be able to see the ASCII characters in the format string
Tell 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

If we have a text string that includes a formatted date object, 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 sample, shown below, will parse the text string
"9-29-2001" and creates a Date object with a value of 001736000000.

Sample 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've been able to 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 obtained four built-in date lattices
The process of processing. They contain 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 number of parameters
is a date style, and the second is a 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 learn about the many other ways and options to get the time and date formatting process, see Sun's web
The explanations on the website.

When executing our sample 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

JAVA Calendar Specific Explanation

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.