October 29, 2020 Since I dealt with the Calendar class in Java, I will briefly summarize how to use it.
A class for manipulating dates and specified dates and times. Used to calculate, get, and set the date and time in Java.
In the Calendar class, create an object by calling the getInstance
method instead of the operator new
. The getInstance method returns an object initialized to the current date and time each time it is called. When using it, be sure to specify ʻimport java.util.Calendar`.
import java.util.Calendar
public class Main {
public static void main(String[] args) throws Exception {
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.get(Calendar.YEAR) + "Year" + calendar.get(Calendar.MONTH)+ "Moon" + calendar.get(Calendar.DATE) + "Day" );
}
}
Execution result
October 29, 2020
The set method is used to set the date and time. Therefore, it is often used in programs that process dates.
Note that in the example below, the previous values will remain except for the specified element (years in this case).
How to use
import java.util.Calendar
public class Main {
public static void main(String[] args) throws Exception {
Calendar calendar = Calendar.getInstance();
System.out.println("Current date and time:" + calendar.getTime().toString());
//Set the year to 2022
calendar.set(Calendar.YEAR, 2022);
System.out.println("Set 2022 for the year:" + calendar.getTime());
}
}
Execution result
Current date and time: Thu Oct 29 10:43:58 UTC 2020
Set the year to 2022: Thu Oct 29 10:43:58 UTC 2022
Use the add method when adding or subtracting dates in the Calendar class.
How to use
import java.util.Calendar
public class Main {
public static void main(String[] args) throws Exception {
Calendar calendar = Calendar.getInstance();
System.out.println("Current date and time:" + calendar.getTime().toString());
//Add 1 year
calendar.add(Calendar.YEAR, 1);
System.out.println("Increase by one year:" + calendae.getTime());
}
}
Execution result
Current date and time: Thu Oct 29 10:43:58 UTC 2020
Increase by 1 year: Thu Oct 29 10:43:58 UTC 2021
You can specify the date format with a character string.
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day");
System.out.println(sdf.format(calendar.getTime()));
}
}
Execution result
October 20, 2020
[Java] How to use the Calendar class that can be used to calculate and get the date and time! [Introduction to Java] Complete explanation of how to use the Calendar class (set / add / format) [Introduction to Java] Specify the date format of Calendar (format) [Introduction to Java] How to use Calendar (add)
Recommended Posts