Algorithm for time, date, week, month (usage of calendar in Java) (i)

Source: Internet
Author: User

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 ();       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 separated" +days+ "days," + "that is, I am on this beautiful planet has been happy life" +days+ "days.      "); }} The static method of the Calendar class getinstance () can initialize a Calendar object: calendar now = CalenDar.getinstance (); Can use the following three methods to set the calendar to no matter what time: set (int year, int month,int date) set (int year, int month,int date,int hour,int minute) se T (int year, int month,int date,int hour,int minute,int second) false conceive of obtaining information such as years, months, and hours can be used: Now.get (calendar.month) This Scenario 0 shows that in January, 1 means February get (calendar.day_of_month) Gets the day of the month get (Calendar.day_of_week) Gets the day of the week get (calendar.day_of_ Year) Gets the day of the Gettimemillis () gets the current time of the millisecond representation for example the following is a simple introduction to the Calendar class method abstract void Add (int field, int amount) based on day      Calendar to add or subtract a specified amount of time for a given date field.      The Boolean after object is inferred whether the time represented by this Calendar returns the inferred result after the time specified by object.      Boolean before (Object when) infers whether the time represented by this Calendar returns the inferred result before the time specified by object.      void Clear () Sets 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.      an int compareTo (calendar Anothercalendar) is a two calendar object representing the time value (from the Calendar element to the current millisecond offset).     protected void complete () fills all fields in the Calendar field that are not set. protected abstract void Computefields () converts the current millisecond time value to the value of the Calendar field 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) to compare this Calendar with the specified Object.      int get (int field) returns the value of the given Calendar field.      int getactualmaximum (int field) gives the time value for this calendar, returning the maximum value that the specified calendar field might have.      int getactualminimum (int field) gives the time value for this calendar, returning 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 the string representation of a calendar field value under a given style and Locale. map<string,integer> getdisplaynames (int field, int style, locale locale) returns a MAP that includes the full name of the Calendar field under a given style and Locale, and      Its corresponding field value.      int Getfirstdayofweek () Gets the first day of the week; For example, in the United States, this day is SUNDAY, and in France, this day is MONDAY.      the 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 using the default time zone and locale.      Static Calendar getinstance (Locale Alocale) obtains 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.      the abstract int getleastmaximum (int field) returns the lowest maximum value for the given Calendar field for this calendar instance.      the 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 one weeks of the year, for example, assuming that the first week of the definition is included in the first month of the year, this method returns 1.      the 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 to the current millisecond offset.      Long Gettimeinmillis () returns the time value of 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.      The Boolean islenient () infers whether 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 already been set because the call to the 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 dayThe Calendar field is set 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) sets the value of the Calendar field 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 field year, month, Day_of_month, HOUR, MIN      The values of UTE and SECOND.      void Setfirstdayofweek (int value) sets 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) sets the minimum number of days that are required for the first one weeks of the year, for example, if the first day of the first month of a year is defined, and then this method is called with a value of 1.      void SetTime (date date) Sets the time of this Calendar using the given date.      void Settimeinmillis (Long Millis) sets the current time value for this Calendar with a given long value.      void Settimezone (TimeZone value) sets the time zone using the given time zone value.   String toString () returns the strings representation of this calendar example of a regular usage of the Calendars 1, calculates 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 objectDefault January is 0 int day=time.getactualmaximum (calendar.day_of_month);//number of days of the month Note: Before using the Set method, you must clear the first, otherwise very much information will inherit from the system  Current time 2, calendar and date conversion (1) Calendar to date calendar cal=calendar.getinstance ();    Date Date=cal.gettime ();  (2) date is converted to Calendar date date=new date ();  Calendar cal=calendar.getinstance ();    Cal.settime (date);  3. Formatted output datetime 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 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) The number of weeks of the year is calculated 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-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);  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, the Roll () method loops within this month, generally using the Add () method; 6, calculate the number of intervals between two random times (1) into the Calendar object/* * calculation Days apart 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 two milliseconds of time respectively long Sl=startday.gettimeinmillis ();        Long El=endday.gettimeinmillis ();          Long EI=EL-SL;  Calculates the interval number of days (int) (ei/(1000*60*60*24)) based on the number of milliseconds; } (2) into the Date object/** calculates the number of days between two time * @param startday start time * @param endday End time * @return */public int Getintervald          Ays (Date startday,date endday) {//ensure startday before Endday if (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 interval number of days (int) (ei/(1000*60*60*24)) based on the number of milliseconds; Similarly, you can use the same method to calculate the number of hours, minutes, seconds, and so on. Note: The above method is completely calculated by time, and sometimes not pleasant, such as: startday= "2006-10-11 20:00:00" endday= "2006-10- 12 8:00:00 "The result of the calculation is 0, but we may have to let the calculation result become 1, at this time can be implemented in the following way: Before the transfer, set the EnddayThe 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); Then it goes in Startday,endday, and the result is as we wish. Just, assuming that the above method is troublesome, can refer to the following methods: (3) To improve the method of accurately calculating the number of days apart public int Getdaysbetween (Calendar d1, calendar D2) {if (d1.a              fter (D2)) {//swap dates so D1 are 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);//Get the actual number of years 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.