Java Calendar and summary

Write this blog to commemorate the first topic of the letcode 177 weekly rollover. The first part is the analysis of the problem, the second part is the use of Java Calendar and points for attention.

1. Topic analysis

1.1 topic

Please write a program to calculate how many days have passed between two dates.
The date is given in string format, YYYY-MM-DD

1.2 way of thinking

Set Calendar after each item of date is converted to int, then use getTimeInMillis method to get the millisecond value from 1970.01.01 to the time, and then subtract to convert to days

1.3 code

public int daysBetweenDates(String date1, String date2) {
         String[] s1=date1.split("-");
         String[] s2=date2.split("-");
         java.util.Calendar c1=java.util.Calendar.getInstance();
         java.util.Calendar c2=java.util.Calendar.getInstance();
         //The following two sentences are not found in the wrong version submitted before 1
         c1.clear();
         c2.clear();
         //The second item after error version c1.set submitted before 2 does not have - 1
         c1.set(Integer.parseInt(s1[0]),Integer.parseInt(s1[1])-1,Integer.parseInt(s1[2]));
         c2.set(Integer.parseInt(s2[0]),Integer.parseInt(s2[1])-1,Integer.parseInt(s2[2]));
        long temp=Math.abs(c1.getTimeInMillis()-c2.getTimeInMillis());
        long ans=temp/(24*60*60*1000);
        return ((int)ans);
    }

1.4 analysis

  1. It is also the most important point that the system time will affect the value of the calendar (such as the current time, minutes and seconds) because the system does not clear before using the set method on the calendar. The test was successful and submitted, and the fantasy happened! The same sample runs different results at the time of testing and submission. The reasons for this situation are: 1. The unified time will affect the value of calendar 2. The division of long will round off the decimal part of the calculation 3. The calculated results are random at different running times.
    PS: I tried c1.set(Integer.parseInt(s1[0]),Integer.parseInt(s1[1])-1,Integer.parseInt(s1[2]),0,0,0) in the middle of the process, and still submitted an error, presumably because this method can only be set to seconds, and milliseconds will also affect the results.
  2. The Calendar month is 0-11. When you save it, subtract 1 to get the correct result

2. Calendar Usage Summary

2 Introduction

Calendar is an abstract class, and Gregorian calendar is a concrete implementation of it. Calendar.getInstance() gets a calendar object initialized at the current time. (example of Gregorian calendar)

2.1 acquisition time

Note that the Calendar.DATE and calendar.day? Of? Month are the same, while the Calendar.HOUR and Calendar.HOUR? Of? Day are not the same

Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        //1 less than current month
        int month = cal.get(Calendar.MONTH);
        //date is the same as day of month
        int date = cal.get(Calendar.DATE);
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        //Indicates the day of the week, counting from Sunday
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
        //12 hour system
        int hour = cal.get(Calendar.HOUR);
        //24 hour system
        int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        int millisecond = cal.get(Calendar.MILLISECOND);
        //Get the last day of this month. getMaximum is the maximum value of the get day. It must be 31
        int maxDate = cal.getActualMaximum(Calendar.DATE);

2.2 setting time

set

set(int field, int value)
field can be used to set the year / month / day / hour / minute / second / microsecond equivalent, such as Calendar.MONTH

set(int year, int month, int day, int hour, int minute, int second)
Note: there is no set(int year, int month, int day, int hour, int minute, int second,int millsecond) function, and the function set to second above will not clear millsecond

Calendar uses the method of delaying calculation for the set() method for performance reasons, that is, multiple sets without multiple calculations are only calculated when the get(), getTime(), getTimeInMillis(), add(), or roll() functions are called. Chestnuts on java document:

Calendar c = Calendar.getInstance();
c.set(2000, 7, 31, 0, 0 , 0); //2000-8-31
c.set(Calendar.MONTH, Calendar.SEPTEMBER); //It should be 2000-9-31, that is, 2000-10-1
c.set(Calendar.DAY_OF_MONTH, 30); //If the Calendar is converted to 2000-10-1, the current result is 2000-10-30
cal1.getTime(); //2000-9-30, it means that you can only calculate after calling get
add
  1. When the modified field is beyond its range, the field larger than it will be automatically modified (for example, line 2 and line 3 of the following example, modify the month and year correction)
  2. When the modified field causes the range of the smaller field to change, the smaller field is adjusted as close to its expected value as possible (as shown in lines 3 and 4 of the following example)
Calendar cal1 = Calendar.getInstance();
cal1.set(1999, 7, 31, 0, 0 , 0); //1999-8-31
cal1.add(Calendar.MONTH, 13); //2000-9-31
System.out.println(cal1.getTime()); //The result is 2000-9-31
roll

When the modified field is beyond its range, the larger field will not be modified

2.3 fault tolerance setting

When a user gives the wrong date, it is automatically calculated, but if Lenient==false, Calendar reports an error

Calendar cal1 = Calendar.getInstance();
cal1.set(2000, 1, 32, 0, 0, 0);
System.out.println(cal1.getTime());//Show as Tue Feb 01 00:00:00 PST 2000
cal1.setLenient(false);
cal1.set(2000, 1, 32, 0, 0, 0);
System.out.println(cal1.getTime());//Report errors
Published 14 original articles, won praise 0, visited 482
Private letter follow

Keywords: Java less

Added by Zanus on Sun, 23 Feb 2020 11:24:39 +0200