1. Java calculates the maximum number of days of a month
1 Calendar time = calendar. getinstance (); // use the default time zone and language environment to get a calendar 2 time. clear (); 3 time. set (calendar. year, year); 4 time. set (calendar. month, I-1); // note that the calendar object default January is 0 of 5 Int day = time. getactualmaximum (calendar. day_of_year); // returns the number of days of the current month.
Note: You must call clear () before using the set method. Otherwise, many information will inherit from the current system time.
2. Conversion of calendar and date in Java
(1) convert calendar to date
1 Calendar cal=Calendar.getInstance();2 Date date=cal.getTime();
(2) convert date to calendar
1 Date date=new Date();2 Calendar cal=Calendar.getInstance();3 cal.setTime();
3. formatting the output Date and Time in Java
1 Date = new date (); 2 simpledateformat df = new simpledateformat ("yyyy-mm-dd hh: mm: SS"); // set the date and time format 3 system. out. println (DF. format (date ));
4. the week of the year in Java computing
(1) Calculate the week number of a day in a year.
1 Calendar cal=Calendar.getInstance();2 cal.set(Calendar.YEAR,2012);3 cal.set(Calendar.MONTH);4 cal.set(Calendar.DAY_OF_MONTH,3);5 int weekno=cal.get(Calendar.WEEK_OF_YEAR);
(2) Calculate the day of the week in a year.
1 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");2 Calendar cal=Calendar.getInstance();3 cal.set(Calendar.YEAR,2012);4 cal.set(Calendar.WEEK_OF_YEAR,1);5 cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);6 System.out.println(df.format(cal.getTime()));
Output result:
2012-01-02
5. Add () and roll () Usage
(1) Add () method
1 simpledateformat df = new simpledateformat ("yyyy-mm-dd"); 2 Calendar Cal = calendar ar. getinstance (); 3 Cal. set (calendar. year, 2012); // set year 4 Cal. set (calendar. month, 5); // set month 5 Cal. set (calendar. day_of_month, 5); 6 Cal. add (calendar. date,-4); 7 Date = Cal. gettime (); 8 system. out. println (DF. format (date); 9 Cal. add (calendar. date, 4); 10 Date = Cal. gettime (); 11 system. out. println (DF. format (date ));
Output result:
2012-06-05
2012-06-01
(2) Roll () method
1 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); 2 Calendar cal=Calendar.getInstance(); 3 cal.set(Calendar.YEAR, 2012); 4 cal.set(Calendar.MONTH,8); 5 cal.set(Calendar.DAY_OF_MONTH, 3); 6 cal.roll(Calendar.DATE,-4); 7 Date date=cal.getTime(); 8 System.out.println(df.format(date)); 9 cal.roll(Calendar.DATE,4);10 date=cal.getTime();11 System.out.println(df.format(date));
Output result:
2012-09-29
2012-09-03
It can be seen that the roll () method loops over the current month, and the add () method is generally used;