The Java Calendar-API
The java.util.Calendar
class in Java is a legacy class that provides utility methods for working with dates and times. It is part of the Java Date-Time API, which is a new API introduced in Java 8 that replaces the legacy java.util.Date
class.
Here are some examples of using the java.util.Calendar
class to work with dates and times in Java:
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// Get the current date and time
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());
// Set a specific date and time
calendar.set(Calendar.YEAR, 2020);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
System.out.println(calendar.getTime());
// Add a specific amount of time to a date and time
calendar.add(Calendar.YEAR, 1);
calendar.add(Calendar.MONTH, 3);
calendar.add(Calendar.DAY_OF_MONTH, 10);
System.out.println(calendar.getTime());
}
}
In this example, the Calendar.getInstance
method is used to get the current date and time, and the set
method is used to set a specific date and time. The add
method is used to add a specific amount of time to a date and time. The getTime
method is used to get the date and time represented by a Calendar
object as a java.util.Date
object.
Note that the java.util.Calendar
class is a legacy class and is not the recommended way of working with dates and times in Java. It is recommended to use the java.time
package instead, which provides a more comprehensive and easy-to-use set of classes for working with dates, times, and durations.