calendar usage

Java中Calendar的使用方法

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("现在时间是:"+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("现在时间是:"+year+"年"+month+"月"+day+"日,星期"+week);
     long year2009=calendar.getTimeInMillis();
     calendar.set(1989,9,26);//The difference between this and the real month is 1
     long year1989=calendar.getTimeInMillis();
     long days=(year2009-year1989)/( 1000*60*60*24);
     System.out.println("Today and October 26, 1989 are separated by "+days+" days, "+" means I have a happy life on this beautiful planet" +days+"Days.");

  }
}
The static method getInstance() of the Calendar class can initialize a calendar object:

Calendar now = Calendar.getInstance();

You can use the following three methods to set the calendar to any 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,int hour,int minute,int second)
If you want to get the year, Month, hour and other information can be used:

Now.get(Calendar.Month) This method 0 means January, 1 means February
get(Calendar.DAY_OF_MONTH) get the 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() get the millisecond representation of the current time
as follows Introduction to Calendar class methods

abstract void add(int field, int amount) Adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar.
boolean after(Object when) Determines whether the time represented by this Calendar is after the time represented by the specified Object, and returns the result.
boolean before(Object when) Determines whether the time represented by this Calendar is before the time represented by the specified Object, and returns the result.
void clear() Sets the calendar field value and time value (offset in milliseconds from the epoch to the present) of this Calendar to undefined.
void clear(int field) Sets this Calendar's given calendar field value and time value (offset in milliseconds from the epoch to the present) to undefined.
Object clone() creates and returns a copy of this object.
int compareTo(Calendar anotherCalendar) Compares the time values ​​(offset in milliseconds from the epoch to the present) represented by two Calendar objects.
protected void complete() fills all unset fields in the calendar field.
protected abstract void computeFields() Converts the current millisecond time value time to the calendar field value in fields[].
protected abstract void computeTime() Converts the current calendar field value in fields[] to the millisecond time value time.
boolean equals(Object obj) Compares this Calendar with the specified Object.
int get(int field) returns the value of the given calendar field.
int getActualMaximum(int field) Given the time value of this Calendar, returns the maximum possible value for the specified calendar field.
int getActualMinimum(int field) Given the time value of this Calendar, returns the smallest possible value for the specified calendar field.
static Locale[] getAvailableLocales() returns an array of all locales for which the getInstance method of this class can return a localized instance.
String getDisplayName(int field, int style, Locale locale) Returns the 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 containing all the names of the calendar fields and their corresponding field values ​​under the given style and locale.
int getFirstDayOfWeek() gets the first day of the week; for example, in the US it is SUNDAY, and in France it is MONDAY.
abstract int getGreatestMinimum(int field) Returns the highest minimum value for the given calendar field for this Calendar instance.
static Calendar getInstance() Gets a calendar with the default time zone and locale.
static Calendar getInstance(Locale aLocale) Gets a calendar using the default time zone and the specified locale.
static Calendar getInstance(TimeZone zone) Gets a calendar with the specified time zone and default locale.
static Calendar getInstance(TimeZone zone, Locale aLocale) Gets a calendar with 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 first week of the year, for example, if the first week is defined to include the first day of the first month of the year, this method will return 1.
abstract int getMinimum(int field) Returns the minimum value of the given calendar field for this Calendar instance.
Date getTime() returns a Date object representing this Calendar's time value (the millisecond offset from the epoch to the present).
long getTimeInMillis() returns the time value for this Calendar in milliseconds.
TimeZone getTimeZone() gets 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() determines whether the interpretation of date/time is loose.
boolean isSet(int field) Determines whether the given calendar field has a value already set, including cases where the value has already been set as a result of a call to the get method triggering an internal field calculation.
abstract void roll(int field, boolean up) Adds or subtracts (up/down) a single time unit on the given time field, without changing the larger field.
void roll(int field, int amount) Adds the specified (signed) amount of time to the specified calendar field, leaving larger fields unchanged.
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 values ​​of the calendar fields YEAR, MONTH and DAY_OF_MONTH.
void set(int year, int month, int date, int hourOfDay, int minute) Sets the values ​​of the 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) Sets the values ​​of the fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE and SECOND.
void setFirstDayOfWeek(int value) Sets the first day of the week; for example, in the US it is SUNDAY, in France it is MONDAY.
void setLenient(boolean lenient) Specifies whether date/time interpretation is lenient.
void setMinimalDaysInFirstWeek(int value) Sets the minimum number of days required for the first week of the year, eg, if the first week is defined to include the first day of the first month of the year, call this method with a value of 1.
void setTime(Date date) Sets this Calendar's time using the given Date.
void setTimeInMillis(long millis) Sets this Calendar's current time value with the given long value.
void setTimeZone(TimeZone value) Sets the time zone with the given time zone value. String toString() Example of a common method for a Calendar
that returns a string representation of this calendar


1. Calculate the maximum number of days in a month

Calendar time=Calendar.getInstance();
time.clear();
time.set(Calendar.YEAR,year);
time.set(Calendar.MONTH,i-1);// Note that the Calendar object defaults to 0 in January            
int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);//The number of days in this month
Note : Before using the set method, you must clear it first, otherwise a lot of information will be inherited from the current system time

2 , Conversion of Calendar and Date

(1) Calendar converted to Date

Calendar cal=Calendar.getInstance();
Date date=cal.getTime();
(2) Date converted to Calendar

Date date=new Date();
Calendar cal=Calendar .getInstance();
cal.setTime(date);
3. Format the output date and time

Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(df.format(date));
4. Calculate the

week of the year (1) Calculate the week of the year that a certain day is

Calendar cal=Calendar.getInstance();
cal.set (Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, ;
cal.set(Calendar.DAY_OF_MONTH, 3);
int weekno=cal.get(Calendar.WEEK_OF_YEAR);
(2) Calculate the day of the year What is the day of the week

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, ;
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.add(Calendar.DATE, -4);
Date date=cal.getTime();
System.out.println(df.format(date));
cal.add(Calendar.DATE, 4);
date=cal.getTime();
System.out.println(df.format(date));
输出:

    2006-08-30
    2006-09-03
(2)roll方法

cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH, ;
cal.set(Calendar.DAY_OF_MONTH, 3);
cal.roll(Calendar.DATE, -4);
date=cal.getTime();
System.out.println(df.format(date));
cal.roll(Calendar.DATE, 4);
date=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 the add() method is generally used;

6. Calculate the number of days between two arbitrary times

(1) Pass it into the Calendar object

/
**calculation 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 is before endday
    if(startday.after(endday) ){
        Calendar cal=startday;
        startday=endday;
        endday=cal;
    }
    //Get the milliseconds of the two times respectively
    long sl=startday.getTimeInMillis();
    long el=endday.getTimeInMillis();

    long ei=el-sl;   
    //calculate the interval days according to the number of milliseconds
    return (int)(ei/(1000*60*60*24)) ;
}
(2) Pass in Date object

/** Calculate 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 is before endday
    if(startday.after(endday)){
        Date cal=startday;
        startday=endday;
        endday=cal;
    }
    //Get the milliseconds of the two times respectively
    long sl=startday.getTime();
    long el =endday.getTime();

    long ei=el-sl;   
    //Calculate the interval days according to the number of milliseconds
    return (int)(ei/(1000*60*60*24));
}
Similarly, you can use the same method to calculate any two time intervals Hours, minutes, seconds, etc.

Note : The above method is completely time-based, sometimes unsatisfactory, such as:

startday="2006-10-11 20:00:00" endday="2006-10- 12 8:00:00 "The

calculation result is 0, but we may let the calculation result become 1. In this case, the following method can be used:

Before passing the parameters, first set the endday time, such as:

endday.set(Calendar. HOUR_OF_DAY, 23);
endday.set(Calendar.MINUTE, 59);
endday.set(Calendar.SECOND, 59);
endday.set(Calendar.MILLISECOND, 59);
so pass in startday, endday, the result is like We got what we wanted. However, if the above method is too troublesome, you can refer to the following methods:

(3) Improve the method of accurately calculating the number of days between

    public int getDaysBetween (Calendar d1, Calendar 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) != y2) {
            d1 = (Calendar) d1.clone();
            do {
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);//得到当年的实际天数
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        }
        return days;
    }


转http://outofmemory.cn/code-snippet/979/Java-Calendar-Date-usage-summary

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326068144&siteId=291194637