(Use the GregorianCalendar class) Java API has the GregorianCalendar class in the java.util package, which you can use to obtain the year, month, and day of a date. The no-arg constructor constructs an instance for the current date, and the methods get(GregorianCalendar.YEAR), get(GregorianCalendar. MONTH), and get(GregorianCalendar.DAY_OF_MONTH) return the year, month, and day. Write a program to perform two tasks: 1.Display the current year, month, and day. 2.The GregorianCalendar class has the setTimeInMillis(long), which can be used to set a specified elapsed time since January 1, 1970. Set the value to 1234567898765L and display the year, month, and day.
时间: 2024-01-29 12:03:43 浏览: 63
Here is the Java program that performs the two tasks as described:
```java
import java.util.GregorianCalendar;
public class GregorianCalendarDemo {
public static void main(String[] args) {
// Display the current year, month, and day
GregorianCalendar calendar = new GregorianCalendar();
int year = calendar.get(GregorianCalendar.YEAR);
int month = calendar.get(GregorianCalendar.MONTH) + 1; // add 1 to get the actual month value
int day = calendar.get(GregorianCalendar.DAY_OF_MONTH);
System.out.println("Current date: " + year + "-" + month + "-" + day);
// Set the elapsed time to 1234567898765L and display the year, month, and day
calendar.setTimeInMillis(1234567898765L);
year = calendar.get(GregorianCalendar.YEAR);
month = calendar.get(GregorianCalendar.MONTH) + 1; // add 1 to get the actual month value
day = calendar.get(GregorianCalendar.DAY_OF_MONTH);
System.out.println("Elapsed time since January 1, 1970: " + year + "-" + month + "-" + day);
}
}
```
The output of this program will be:
```
Current date: 2021-4-21
Elapsed time since January 1, 1970: 2009-2-13
```
Note that the current date will depend on your system clock, but the elapsed time since January 1, 1970 will always be the same.
阅读全文