Home >Java >javaTutorial >How to use Calendar function for date operations in Java
Java is a very powerful programming language and also provides a wealth of date operation functions, including the Calendar function. The Calendar function can help us perform various operations on dates.
Calendar is an abstract class, we need to use the getInstance method to get the Calendar instance. The properties of the Calendar object include year, month, day, hour, minute, second, etc. We can use them to represent dates.
The following are the specific details of how to use the Calendar function for date operations:
We can use the getInstance method to get the current date. The following is the code for this process:
Calendar cal = Calendar.getInstance();
The cal object returned is the Calendar instance of the current date.
We can use the set method to set a specific date. The following code sets the date to November 11, 2021:
cal.set(Calendar.YEAR, 2021); cal.set(Calendar.MONTH, 10); cal.set(Calendar.DAY_OF_MONTH, 11);
Note that since the MONTH attribute starts counting from 0, the corresponding number for November is 10.
We can use the get method to get the attribute value of a specific date:
int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); // 注意,由于MONTH属性从0开始计算,因此1月对应的数字是0。 int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND);
We can use the getTimeInMillis method to get the timestamp of the date represented by the Calendar object, so that we can calculate the difference between dates. The following code calculates the number of days between two dates:
Calendar startCal = Calendar.getInstance(); startCal.set(Calendar.YEAR, 2021); startCal.set(Calendar.MONTH, 10); startCal.set(Calendar.DAY_OF_MONTH, 1); // 2021年11月1日 Calendar endCal = Calendar.getInstance(); endCal.set(Calendar.YEAR, 2021); endCal.set(Calendar.MONTH, 10); endCal.set(Calendar.DAY_OF_MONTH, 5); // 2021年11月5日 long startTime = startCal.getTimeInMillis(); long endTime = endCal.getTimeInMillis(); long diffTime = endTime - startTime; long diffDays = diffTime / (1000 * 60 * 60 * 24); // 计算天数
In the above code, 1000 60 60 * 24 is the number of milliseconds in a day.
We can use the add method to add and subtract dates. The parameters passed include the fields to be added and subtracted and the fields to be added and subtracted. value. The following code adds 10 days to the current date:
cal.add(Calendar.DAY_OF_MONTH, 10);
The above are the specific details of how to use the Calendar function for date operations. By using the Calendar function, we can easily perform various operations on dates, which is very convenient and practical.
The above is the detailed content of How to use Calendar function for date operations in Java. For more information, please follow other related articles on the PHP Chinese website!