Java Date time Java.util.Calendar and GregorianCalendar analysis

Source: Internet
Author: User
Tags abstract comparison current time dateformat time zones reset

Java Java.util.Calendar is used for date and time operations. Use this class whenever you have some minor actions (other than just the date and time) that you need to perform. (Original: Whenever you have something slightly more advanced than just representing a date and time, "This is the" class to use. )


The Java.util.Calendar class is abstract, meaning that you cannot instantiate it. The reason for this design is that the world has multiple calendars. For example, the Arabic calendar uses a different calendar year than most Western countries to use as its first year.


(Translator Note: about the current Gregorian calendar, reprinted wiki content is as follows: the current Gregorian calendar (Latin: Calendarium gregorianum, also known as Gregorian, also translated country Swiss calendar, the amount of my calendar, Gregorian, Gregorian calendar), is by the Italian doctor and philosopher Aloi Rilliouse reformed the calendar developed by the Julian calendar, enacted by Pope Gregorian 13 in 1582. Gregorian calendar is one of the Gregorian calendar, began in 1912 in China formally adopted to replace the traditional Chinese calendar, and the traditional Chinese calendar is a lunisolar, so the Gregorian calendar in Chinese also known as the Gregorian calendar, Western calendar, new calendar. Gregorian as in the Julian calendar, the Gregorian calendar is also a leap day every four years at the end of February, but Gregorian specifically stipulates that, unless divisible by 400, all the centuries (divisible by 100) do not set a leap day; So, every 400 years, the Gregorian calendar has only 97 leap year, which is 3 fewer than the Julian calendar. )

Instantiation of GregorianCalendar

Java is only carrying the implementation of the Gregorian calendar, that is the Java.util.GregorianCalendar class, the following is an example of how you instantiate GregorianCalendar:

Calendar calendar = new GregorianCalendar ();

A new GregorianCalendar has a date and time that is set to the current point in time, indicating that it was created.

get the year, month, day, etc

The Calendar class has some pairs of methods that let you get time zones for years, months, days, hours, minutes, seconds, milliseconds, and given dates. Here are some examples of how to get here:

Calendar calendar = new GregorianCalendar ();

int year = Calendar.get (calendar.year);
int month = Calendar.get (calendar.month);
int dayofmonth = Calendar.get (calendar.day_of_month); 0, not 1
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); Hour clock
int hourofday = Calendar.get (Calendar.hour_of_day); Hour clock
int minute = Calendar.get (Calendar.minute);
int second = Calendar.get (Calendar.second);
int millisecond= calendar.get (calendar.millisecond);


You can also access more fields, such as Day_of_week_in_month and AM_PM, which are not commonly used. You can check out the official Javadoc for more information about these fields.


The Calendar class has the corresponding set method, so you can also set the fields. Here is an example of what it looks like:

Calendar calendar = new GregorianCalendar ();

Calendar.set (Calendar.year, 2009);
Calendar.set (Calendar.month, 11); one = December
Calendar.set (Calendar.day_of_month, 24); Christmas Eve


add and reduce years, months, days, etc.

You can also add values to these fields and allow the calendar instance to update itself accurately. Take a look at the following example:

Calendar calendar = new GregorianCalendar ();

Set date to last day of 2009
Calendar.set (Calendar.year, 2009);
Calendar.set (Calendar.month, 11); one = December
Calendar.set (Calendar.day_of_month, 31); New Years Eve

Add one day
Calendar.add (Calendar.day_of_month, 1);

The date is now a. 1st 2010
int year = Calendar.get (calendar.year); Now 2010
int month = Calendar.get (calendar.month); Now 0 (a few more than 0)
int dayofmonth = Calendar.get (calendar.day_of_month); Now 1


The Add method is very handy when you are doing some date arithmetic. For example, add or decrease the number of years, months, days, hours, etc. on a given date.
Reduce values on these fields by calling the Add method with negative values, such as:

Calendar.add (Calendar.day_of_month,-1);

Traps and myths

There are some small traps in the Calendar class that you should know to avoid unnecessary brain damage. I will discuss them in the next section.

Month Traps

The month field for the Calendar class is not 1 to 12 as we write the date elsewhere. Instead, the month goes from 0 to 11,0, January, and 11 to December. If you do not know this, it will cause a little error and the debugging that comes with it.


A few misunderstandings of the week

As you would expect, the week goes from 1 to 7, but the first day of the week is Saturday instead of Monday. This means 1 = Sunday, 2 = Monday, ..., 7 = Saturday. It also makes me feel a bit annoyed from time to time.



Time operations for Java Calendar classes

Java Calendar class time operation, the code is very simple.

Shows the time to get, the cumulative and the decrement of the date time.

package mytest;
/*  *  demo  Calendar  general Operations  */import java.util.date;
import java.text.simpledateformat;
import java.text.dateformat;
import java.util.calendar; public class test {  public test ()   {  }   public  Static void main (String[] args)   {    //  string conversion date format      // dateformat fmtdatetime = new simpledateformat ("yyyy-MM-dd 
HH:mm:ss ");     //  Get date format Objects     // Date date = 
Fmtdatetime.parse (Strdatemake);     //  Full Display date time     String str =  (new 
SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss:sss")). Format (New date ());
    system.out.println (str);     //  Create  Calendar  Object     calendar&Nbsp;calendar = calendar.getinstance ();     //  Initialize  Calendar  object, but not necessary unless reset time is required     
Calendar.settime (New date ());     // setTime  Similar line above     // Date date = 
New date ();
    // calendar.settime (date);     //  Show Year     int year = calendar.get (
Calendar.year);
    system.out.println ("year is = "  + string.valueof (year));     //  Show Month   (starting from 0,  actual display to add a)     int month =
 calendar.get (Calendar.month);
    system.out.println ("month is = "  +  (month + 1));     //   N  Day of the year     int DAY_OF_YEAR = 
Calendar.get (calendar.day_of_year);   &nbsP; system.out.println ("day_of_year is = "  + day_of_year);     //  this month  N  day     int DAY_OF_MONTH = 
Calendar.get (Calendar.day_of_month);     system.out.println ("day_of_month = "  + string.valueof (DAY_OF_MONTH
));
    // 3 hours later     calendar.add (calendar.hour_of_day, 3);
    int hour_of_day = calendar.get (Calendar.hour_of_day);
    system.out.println ("hour_of_day + 3 = "  + HOUR_OF_DAY);     //  current number of minutes     int minute = calendar.get (
Calendar.minute);
    system.out.println ("minute = "  + minute);
    // 15  minutes after     calendar.add (CALENDAR.MINUTE, 15);     minuTe = calendar.get (Calendar.minute);
    system.out.println ("minute + 15 = "  + MINUTE);
    // 30 minutes ago     calendar.add (calendar.minute, -30);
    minute = calendar.get (Calendar.minute);
    system.out.println ("minute - 30 = "  + MINUTE);     //  formatted display     str =  (New simpledateformat ("
Yyyy-mm-dd hh:mm:ss:ss ")). Format (Calendar.gettime ());
    system.out.println (str);     //  Reset  Calendar  Display current time     calendar.settime (new 
Date ());     str =  (New simpledateformat ("Yyyy-mm-dd hh:mm:ss:ss")). Format (
Calendar.gettime ());
    system.out.println (str);     //  Create a  Calendar  to compare time &NBsp;   calendar calendarnew = calendar.getinstance ();     //  set to  5  hours ago, the latter large, showing  -1     calendarnew.add (
CALENDAR.HOUR, -5);
    system.out.println ("Time Comparison:"  + calendarnew.compareto (Calendar));     //  set 7 hours later, the former is large, showing  1     calendarnew.add (Calendar.hour,
 +7);
    system.out.println ("Time Comparison:"  + calendarnew.compareto (Calendar));     //  return  2  hours, same time, display  0     calendarnew.add (
CALENDAR.HOUR, -2);
    system.out.println ("Time Comparison:"  + calendarnew.compareto (Calendar));  &NBSP}}



A summary of Calendar class and GregorianCalendar Gregorian class usage

The Calendar class mainly involves two classes, one is the abstract class calendar class, and the other is his subclass GregorianCalendar.


one, Calendar class.

1, main fields:

Year (years) MONTH (month starting from 0) DATE (Day of January) HOUR (indicates hours in the morning or afternoon)

Hour_f_day (indicates the hours of the day.) Day_of_week (one day in one weeks) day_of_month (one day in one months) day_of_year (one day of the year)

Day_of_week _in_month (weeks ordinal of one months) Week_of_month (indicates the number of weeks in the current month) Week_of_year (indicates the number of weeks in the current year)
2, Get Calendar class object.

GetInstance is obtained through the static method of the Calendar class.

Calendar CA = Calendar.getinstance ();


3, the Main method

void set (int field,int value)//field The parameters of the Calendar class, such as year MONTH DATE ...

void set (int year,int month,int date)/Set month day.

void Set (int year, int month, int date, int hourofday, int minute)/Set year date

void Set (int year, int month, int date, int hourofday, int minute, int second)//set Date and time

void SetTime (date date);//The time of this Calendar is set using the given Date.



int get (int field)//Returns the value of the given Calendar field. such as: Int month = Acobj.get (calendar.month);

Date getTime ()//Returns a Date object that represents this Calendar time value.

Long Gettimeinmillis ()//Returns the number of milliseconds from 1970.1.1 00:00:00 to the calendar.



void Add (int field,amont);//To add or subtract the specified amount of time for the given calendar field, based on the rules of the calendar. Can be added and reduced. such as: Caobj.add (calendar.month,1) under one months.

second, GregorianCalendar class.

1, Get the class object

The Calendar CA = new GregorianCalendar ()//default current moment.

The Calendar CA = new Gregoriancanlendar (int year,int month,int dayofmonth)//The Gregorian class object that initially has the specified year and month.

The Calendar CA = new Gregoriancanlendar (int year,int month,int dayofmonth,int hourofday,int minute) initially has a Gregorian class object of the specified year and month.

Calendar CA = new Gregoriancanlendar (int year,int month,int dayofmonth,int hourofday,int minute,int)// The Gregorian class object that initially has the specified year and month.

All above are to get the default locale and the default time zone object.


2, usage

The usage mainly inherits to the parent class calendar.

Attach a demo program:

package calendar;
import java.util.calendar;
import java.util.gregoriancalendar; public class calendardemo {    /**      * @ Param args      */    public static void main ( String[] args)  {        //gets a calendar object     
    calendar ca = calendar.getinstance ();
        ca.setfirstdayofweek (Calendar.saturday);
        display (CA);                                     //Create calendar objects for 2012.12.12.12, 12,12         calendar c2 = new gregoriancalendar ( 2012, 11, 12, 12, 12, 12);
        display (CA);                     
      //the number of days separated by the number of days in the year.         int days = c2.get (Calendar.DAY_OF_YEAR)-ca.get (
Calendar.day_of_year);
        system.out.println ("Difference" +days+ "Day");                            //time to reset C2 objects         
System.out.println ("+++++++++++++++++ time ++++++++++++ after reset:");         c2.set (2012,11,23);/month and date are all beginning with 0. The month of 0 means January.
The date of the month, 0 represents the day.
        c2.set (calendar.hour, 22);         c2.set (Calendar.minute, 12);
        c2.set (CALENDAR.SECOND, 12);
        display (C2);                     
      SYSTEM.OUT.PRINTLN ("+++++++++++++++++ Modified time ++++++++++++:");         //29 days Back         
Ca.add (calendar.day_of_year,29);
        display (CA);         //extended 10 hours         
Ca.add (CALENDAR.HOUR, 4);
        display (CA);    &NBSP}     public static void display (CALENDAR CA)  {        string []mon = {"January", "February", "March", "April", "May" , "June", "July", "August", "September", "October", "TenJanuary "," December "};           string []week = {" "," Sunday
"," Monday "," Tuesday "," Wednesday "," Thursday "," Friday "," Saturday "};
        system.out.print (Ca.get (calendar.year) + "year");
        system.out.print (Mon[ca.get (Calendar.month)));
        system.out.print (Ca.get (calendar.day_of_month) + "Day");
        system.out.println (Week[ca.get (Calendar.DAY_OF_WEEK)));
        system.out.print ("Time:");
        system.out.print (Ca.get (Calendar.hour_of_day) + ":");
        system.out.print (Ca.get (Calendar.minute) + ":");
        system.out.println (Ca.get (Calendar.second));                 &nbsP    &NBSP}}


Run Result:  

December 8, 2012 Saturday
Time: 20:42:38
December 8, 2012 Saturday
Time: 20:42:38
A difference of 4 days
+++++++++++++++++ time ++++++++++++:
December 24, 2012 Monday
Time: 10:12:12
+++++++++++++++++ Modified Time ++++++ ++++++:
January 6, 2013 Sunday
Time: 20:42:38
January 7, 2013 Monday
Time: 0:42:38

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.