How to use calendar in Java
package cn.outofmemory.codes.date;import java.util.calendar;import java.util.date;public Class calendardemo { public static void main (String[] args) { calendar calendar=calendar.getinstance (); Calendar.settime (New date ()); system.out.println ("Now Time is:" +new Date ()); string year=string.valueof (Calendar.get (calendar.year)); string month=string.valueof (Calendar.get (calendar.month) +1); String day=string.valueof (Calendar.get (calendar.day_of_month)); string Week=string.valueof (Calendar.get (Calendar.day_of_week)-1); system.out.println (" Now time is: "+year+" year "+month+" month "+day+" Day, Week "+week); long year2009= Calendar.gettimeinmillis (); &nbSp; calendar.set (1989,9,26);//The difference between this and the real month 1 long year1989= Calendar.gettimeinmillis (); long days= (year2009-year1989)/(1000*60*60*24); system.out.println ("Today and October 26, 1989 separated" +days+ "days," + "that is, I am on this beautiful planet has been happy life" +days+ "day. "); }}
The static method of the Calendar class getinstance () can initialize a calendar object:
Calendar now = Calendar.getInstance();
You can use the following three methods to set the calendar to any one time:
Set (int year, Int. month,int date) Set (int year, int month,int date,int hour,int minute) set (int year, int month,int date,i NT Hour,int minute,int Second)
If you want to get the year, month, hour and other information you can use:
Now.get(Calendar.Month)This method 0 means January, 1 means February
get(Calendar.DAY_OF_MONTH)Get the first day of the month
get(Calendar.DAY_OF_WEEK)Get the day of the week
get(Calendar.DAY_OF_YEAR)Get the day of the year
getTimeMillis()Gets the millisecond representation of the current time
Here is an introduction to the Calendar class method
abstract void add(int field, int amount)Adds or subtracts a specified amount of time for a given calendar field, based on the rules of the calendar.
boolean after(Object when)Determines whether the time that this Calendar represents is returned after the specified Object represents the time that the result is judged.
boolean before(Object when)Determines whether the time represented by this Calendar returns the judging result before the time specified by Object.
void clear()Set the Calendar field value and time value for this calendar (from the calendar to the current millisecond offset) to undefined.
void clear(int field)Sets the given Calendar field value and time value for this calendar (from the calendar to the current millisecond offset) to undefined.
Object clone()Creates and returns a copy of this object.
int compareTo(Calendar anotherCalendar)Compares the time values represented by two calendar objects (from the calendar to the current millisecond offset).
protected void complete()Fills all the fields in the Calendar field that are not set.
protected abstract void computeFields()Converts the current millisecond time value to the Calendar field value in fields[].
protected abstract void computeTime()Converts the value of the current Calendar field in fields[] to the millisecond time value.
boolean equals(Object obj)Compares this Calendar with a specified Object.
int get(int field)Returns the value of the given Calendar field.
int getActualMaximum(int field)Given the time value for this calendar, returns the maximum value that the specified calendar field might have.
int getActualMinimum(int field)Given the time value for this calendar, returns the minimum value that the specified calendar field might have.
static Locale[] getAvailableLocales()Returns an array of all locales that the getinstance method of this class can return to a localized instance.
String getDisplayName(int field, int style, Locale locale)Returns a string representation of the Calendar field value under the given style and locale.
Map<String,Integer> getDisplayNames(int field, int style, Locale locale)Returns a Map with all the names of the Calendar field and its corresponding field values under the given style and locale.
int getFirstDayOfWeek()Get the first day of the week; For example, in the United States, this day is SUNDAY, and in France, this day is MONDAY.
abstract int getGreatestMinimum(int field)Returns the highest minimum value for the given Calendar field for this calendar instance.
static Calendar getInstance()Get a calendar using the default time zone and locale.
static Calendar getInstance(Locale aLocale)Get a calendar using the default time zone and the specified locale.
static Calendar getInstance(TimeZone zone)Gets a calendar using the specified time zone and default locale.
static Calendar getInstance(TimeZone zone, Locale aLocale)Gets a calendar using the specified time zone and locale.
abstract int getLeastMaximum(int field)Returns the lowest maximum value for the given Calendar field for this calendar instance.
abstract int getMaximum(int field)Returns the maximum value for the given Calendar field for this calendar instance.
int getMinimalDaysInFirstWeek()Gets the minimum number of days required for the one week of the year, for example, if the first day of the first month of the year is defined, this method returns 1.
abstract int getMinimum(int field)Returns the minimum value for the given Calendar field for this calendar instance.
Date getTime()Returns a Date object that represents this calendar time value, from the calendar element to the current millisecond offset.
long getTimeInMillis()Returns the time value, in milliseconds, for this Calendar.
TimeZone getTimeZone()Get the time zone.
int hashCode()Returns the hash code for this calendar.
protected int internalGet(int field)Returns the value of the given Calendar field.
boolean isLenient()Determine if the date/time interpretation is loose.
boolean isSet(int field)Determines whether a given calendar field has a value set, including cases where the value has been set because the call to get method triggers an internal field calculation.
abstract void roll(int field, boolean up)Adds or subtracts (up/down) a single time cell on a given time field without changing the larger field.
void roll(int field, int amount)Adds a specified (signed) amount of time to the specified calendar field without changing the larger field.
void set(int field, int value)Sets the given Calendar field to the given value.
void set(int year, int month, int date)Sets the value of the Calendar field year, MONTH, and Day_of_month.
void set(int year, int month, int date, int hourOfDay, int minute)Set the values for calendar fields year, MONTH, Day_of_month, Hour_of_day, and MINUTE.
void set(int year, int month, int date, int hourOfDay, int minute, int second)Set the values for the year, MONTH, Day_of_month, HOUR, MINUTE, and SECOND fields.
void setFirstDayOfWeek(int value)Set the day of the first day of the week; For example, in the United States, this day is SUNDAY, and in France, this day is MONDAY.
void setLenient(boolean lenient)Specifies whether the date/time interpretation is loose.
void setMinimalDaysInFirstWeek(int value)Set the minimum number of days required for the first one weeks of the year, for example, if you define the first day of the first month of the year with a value of 1, call this method.
void setTime(Date date)Sets the time of this Calendar with the given Date.
void setTimeInMillis(long millis)Sets the current time value for this Calendar with the given long value.
void setTimeZone(TimeZone value)Sets the time zone using the given time zone value.
String toString()Returns the string representation of this calendar
Examples of common methods for calendar
1. Calculate the maximum number of days for a January
Calendar time=calendar.getinstance (); Time.clear (); Time.set (calendar.year,year); Time.set (calendar.month,i-1);///Note that the Calendar object default January is 0 int day=time.getactualmaximum (calendar.day_of_month);//This month Days
Note: Before using the Set method, you must clear it, otherwise many of the information will inherit from the current time of the system
2. Conversion of calendar and date
(1) Calendar converted to date
Calendar cal=calendar.getinstance ();D ate date=cal.gettime ();
(2) Date converted to Calendar
Date Date=new date (); Calendar cal=calendar.getinstance (); Cal.settime (date);
3. Formatted output date time
Date Date=new date (); SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); System.out.println (Df.format (date));
4. Calculate the first week of the year
(1) Calculate a day is the first week of the year
Calendar cal=calendar.getinstance (); Cal.set (Calendar.year, 2006); Cal.set (Calendar.month, 8); Cal.set (Calendar.DAY_ Of_month, 3); int weekno=cal.get (calendar.week_of_year);
(2) Calculate the number of weeks of the year
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd"); Calendar cal=calendar.getinstance (); Cal.set (Calendar.year, 2006); Cal.set (calendar.week_of_year, 1); Cal.set ( Calendar.day_of_week, Calendar.monday); System.out.println (Df.format (Cal.gettime ()));
Output:
2006-01-02
5. Usage of Add () and Roll ()
(1) Add () method
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd"); Calendar cal=calendar.getinstance (); Cal.set (Calendar.year, 2006); Cal.set (Calendar.month, 8); Cal.set (Calendar.DAY_ Of_month, 3); Cal.add (Calendar.date,-4);D ate date=cal.gettime (); System.out.println (Df.format (date)), Cal.add (Calendar.date, 4);d ate=cal.gettime (); System.out.println (Df.format (date));
Output:
2006-08-30 2006-09-03
(2) Roll method
Cal.set (Calendar.year, 2006); Cal.set (Calendar.month, 8); Cal.set (Calendar.day_of_month, 3); Cal.roll (Calendar.DATE, -4);d ate=cal.gettime (); System.out.println (Df.format (date)), Cal.roll (Calendar.date, 4);d ate=cal.gettime (); System.out.println (Df.format (date));
Output:
2006-09-29 2006-09-03
It can be seen that the roll () method loops within this month and generally uses the Add () method;
6. Calculate the number of intervals between two and any time
(1) Pass into calendar object
/** calculates the number of days between two times * @param startday start time * @param endday End time * @return */public int getintervaldays ( Calendar startday,calendar endday) { //ensure startday before Endday if (Startday.after (endday)) { calendar cal=startday; startday=endday; endday=cal; } //get the number of milliseconds for two time respectively long sl=startday.gettimeinmillis (); long el=endday.gettimeinmillis (); long ei=el-sl; //the number of days between intervals based on milliseconds return (int) (ei/(1000*60*60*24));}
(2) pass in the Date object
/** calculates the number of days between two times * @param startday start time * @param endday End time * @return */public int getintervaldays (Date startday,date endday) { //Make sure StartDay if before Endday ( Startday.after (endday)) { date cal=startday; startday=endday; endday=cal } //get two milliseconds of time respectively long sl= Startday.gettime (); long el=endday.gettime (); long ei= el-sl; //calculates the number of days between intervals return (int) based on the number of milliseconds ( ei/(1000*60*60*24));}
Similarly, you can use the same method to calculate the number of hours, minutes, seconds, etc. of any two time intervals
Note: The above method is completely time-based, and sometimes not satisfactory, such as:
startday= "2006-10-11 20:00:00" endday= "2006-10-12 8:00:00"
The result is 0, but we may be able to make the calculation result 1, which can be implemented as follows:
Before you pass the parameter, set the Endday time, such as:
Endday.set (Calendar.hour_of_day), Endday.set (Calendar.minute, (); Endday.set (Calendar.second); Endday.set ( Calendar.millisecond, 59);
Then it goes in Startday,endday, and the result is as we wish. However, if the above method is troublesome, you can refer to the following methods:
(3) Improve the method of accurately calculating the number of days apart
public int getDaysBetween (CALENDAR&NBSP;D1,&NBSP;CALENDAR&NBSP;D2) { if (D1.after (D2)) { // swap dates so that d1 is start and d2 is end java.util.Calendar swap = d1; d1 = d2; d2 = swap; } int days = d2.get (Calendar.DAY_OF_YEAR) - d1.get (calendar.day_of_year); int y2 = D2.get (calendar.year); if (D1.get (Calendar.YEAR) != &NBSP;Y2) &NBSP;{&NBSP;&NBsp; d1 = (Calendar) d1.clone (); do { days += d1.getactualmaximum ( Calendar.day_of_year)//Get actual days of the year d1.add (calendar.year, 1); } while (D1.get (calendar.year) != y2); } return days; }
Java Calendar Date Usage Summary