Calendar time class in java

Source: Internet
Author: User
Tags time in milliseconds

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 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 obtain the year, month, hour, and other information, you can use:
Now. get (Calendar. Month); in this way, 0 indicates January 1, January, and 1 indicates January 1, 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 () returns the millisecond representation of the current time

 

 

Abstract void add (int field, int amount)
Add or subtract the specified time amount for the specified calendar field according to the calendar rule.
Boolean after (Object when)
Determines whether the time indicated by this Calendar is returned after the time indicated by the specified Object.
Boolean before (Object when)
Returns the result of determining whether the time indicated by this Calendar is prior to the time indicated by the specified Object.
Void clear ()
Set the value of the Calendar field and time (the offset from the time period to the current time in milliseconds) of this Calendar ar to undefined.
Void clear (int field)
Set the given Calendar field value and Time Value (millisecond offset from the Calendar element to the present) of the Calendar ar to undefined.
Object clone ()
Create and return a copy of this object.
Int compareTo (Calendar anotherCalendar)
Compare the time value represented by two Calendar objects (from the time element to the current millisecond offset ).
Protected void complete ()
Fill in all unspecified fields in the calendar field.
Protected abstract void computeFields ()
Converts the current millisecond time value to the calendar field value in fields.
Protected abstract void computeTime ()
Convert the current calendar field value in fields [] to the time value in milliseconds.
Boolean equals (Object obj)
Compare the Calendar with the specified Object.
Int get (int field)
Returns the value of a given calendar field.
Int getActualMaximum (int field)
Given the time value of this Calendar, the maximum value that a specified Calendar field may have is returned.
Int getActualMinimum (int field)
Given the time value of this Calendar, the minimum possible value of the specified Calendar field is returned.
Static Locale [] getAvailableLocales ()
Returns an array of all language environments. The getInstance method of this class can return localized instances for it.
String getDisplayName (int field, int style, Locale locale)
Returns the string representation of the calendar field Values in the given style and locale.
Map <String, Integer> getDisplayNames (int field, int style, Locale locale)
Returns the Map containing all calendar field names and corresponding field values in the given style and locale.
Int getFirstDayOfWeek ()
Obtain the first day of a week. For example, in the United States, this day is SUNDAY, while in France, this day is MONDAY.
Abstract int getGreatestMinimum (int field)
Returns the maximum and minimum values of a given Calendar field in this Calendar instance.
Static Calendar getInstance ()
Use the default time zone and language environment to get a calendar.
Static Calendar getInstance (Locale aLocale)
Use the default time zone and the specified language environment to obtain a calendar.
Static Calendar getInstance (TimeZone zone)
Use the specified time zone and the default language environment to obtain a calendar.
Static Calendar getInstance (TimeZone zone, Locale aLocale)
Obtain a calendar using the specified time zone and language environment.
Abstract int getLeastMaximum (int field)
Returns the minimum maximum value of a Calendar field specified by this Calendar instance.
Abstract int getMaximum (int field)
Returns the maximum value of a specified Calendar field in the Calendar instance.
Int getMinimalDaysInFirstWeek ()
Obtain the minimum number of days required for the first week of a year. For example, if the first week contains the first day of the first month of a year, this method returns 1.
Abstract int getMinimum (int field)
Returns the minimum value of the specified Calendar field in the Calendar instance.
Date getTime ()
Returns a Date object that represents the Calendar time value (offset from the Calendar element to the current millisecond.
Long getTimeInMillis ()
Returns the time value of this Calendar, in milliseconds.
TimeZone getTimeZone ()
Obtain the time zone.
Int hashCode ()
Returns the hash code of the calendar.
Protected int internalGet (int field)
Returns the value of a given calendar field.
Boolean isLenient ()
Determine whether the interpretation of the date/time is loose.
Boolean isSet (int field)
Determine whether a value has been set for the given calendar field, including the setting of this value because the get method is called to trigger the calculation of internal fields.
Abstract void roll (int field, boolean up)
Add or subtract (top/bottom) a single time unit on a given time field without changing the larger field.
Void roll (int field, int amount)
Add the specified (Signed) Time to the specified calendar field without changing the larger field.
Void set (int field, int value)
Set the given calendar field to a given value.
Void set (int year, int month, int date)
Set the values of the calendar fields YEAR, MONTH, and DAY_OF_MONTH.
Void set (int year, int month, int date, int hourOfDay, int minute)
Set 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)
Set the values of YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, and SECOND.
Void setFirstDayOfWeek (int value)
Set the day on the first day of a week. For example, in the United States, this day is SUNDAY, while in France, this day is MONDAY.
Void setLenient (boolean lenient)
Specify whether the date/time interpretation is loose.
Void setMinimalDaysInFirstWeek (int value)
Set the minimum number of days required for the first week of the year. For example, if the first week contains the first day of the first month of the year, use value 1 to call this method.
Void setTime (Date date)
Use the given Date to set the time of this Calendar.
Void setTimeInMillis (long millis)
Set the current time value of the Calendar with the given long value.
Void setTimeZone (TimeZone value)
Use the given time zone value to set the time zone.
String toString ()
Returns the string representation of the 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 is 0 by default
Intday = time. getActualMaximum (Calendar. DAY_OF_MONTH); // number of days of the current month
Note: before using the set method, you must clear it first. Otherwise, many information will inherit from the current system time.
2. Conversion of Calendar and Date
(1) convert Calendar to Date
Calendar cal = Calendar. getInstance ();
Date date = cal. getTime ();
(2) convert Date 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 number of a day in a 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 in a 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. add () and roll () Usage
(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 );
Date date = cal. getTime ();
System. out. println (df. format (date ));
Cal. add (Calendar. DATE, 4 );
Date = cal. getTime ();
System. out. println (df. format (date ));
Output:
2006-0
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 );
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-0
It can be seen that the roll () method loops over the current month, and the add () method is generally used;
6. Calculate the number of days between two arbitrary periods.
(1) upload to the Calendar Object

/***** // Calculate the number of days between two time periods
* @ Param startday Start Time
* @ Param endday End Time
* @ Return
*/
Public int getIntervalDays (Calendar startday, Calendar endday )...{
// Make sure that startday is before endday
If (startday. after (endday ))...{
Calendar cal = startday;
Startday = endday;
Endday = cal;
}
// Obtain the number of milliseconds for each time.
Long sl = startday. getTimeInMillis ();
Long el = endday. getTimeInMillis ();

Long ei = el-sl;
// Calculate the number of days in milliseconds
Return (int) (ei/(1000*60*60*24 ));
}

(2) input Date object

/***** // Calculate the number of days between two time periods
* @ Param startday Start Time
* @ Param endday End Time
* @ Return
*/
Public int getIntervalDays (Date startday, Date endday )...{
// Make sure that startday is before endday
If (startday. after (endday ))...{
Date cal = startday;
Startday = endday;
Endday = cal;
}
// Obtain the number of milliseconds for each time.
Long sl = startday. getTime ();
Long el = endday. getTime ();

Long ei = el-sl;
// Calculate the number of days in milliseconds
Return (int) (ei/(1000*60*60*24 ));
}

Similarly, you can use the same method to calculate the number of hours, minutes, And seconds between two different time periods.
Note: The above method is completely time-based, and sometimes it is not satisfactory, for example:
Startday = "20:00:00"
Endday = "8:00:00"
The calculation result is 0, but we may change the calculation result to 1. You can use the following method to achieve this:
Before passing parameters, set the endday time, for example:
Endday. set (Calendar. HOUR_OF_DAY, 23 );
Endday. set (Calendar. MINUTE, 59 );
Endday. set (Calendar. SECOND, 59 );
Endday. set (Calendar. MILLISECOND, 59 );
In this way, input startday and endday, and the result will be as expected. However, if the above method is too difficult, you can refer to the following method:
(3) improved methods for accurate calculation of days separated

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); // obtain the actual number of days of the current year.
D1.add (Calendar. YEAR, 1 );
} While (d1.get (Calendar. YEAR )! = Y2 );
}
Return days;
}

 

Related Article

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.