Java创建一个可以设置指定年月日时分秒的类
时间: 2023-08-13 22:08:35 浏览: 244
可以使用Java自带的Calendar类来创建一个可以设置指定年月日时分秒的类,如下所示:
```java
import java.util.Calendar;
public class MyDateTime {
private int year;
private int month;
private int day;
private int hour;
private int minute;
private int second;
public MyDateTime(int year, int month, int day, int hour, int minute, int second) {
this.year = year;
this.month = month;
this.day = day;
this.hour = hour;
this.minute = minute;
this.second = second;
}
public void setDateTime() {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month-1, day, hour, minute, second);
System.out.println("设置的时间为:" + calendar.getTime().toString());
}
public static void main(String[] args) {
MyDateTime dateTime = new MyDateTime(2021, 8, 31, 14, 30, 0);
dateTime.setDateTime();
}
}
```
在上述代码中,我们定义了一个MyDateTime类来表示指定的日期时间,构造方法中传入年月日时分秒等参数,然后使用Calendar类来设置日期时间并输出设置后的时间。在main函数中,我们创建了一个时间对象并调用setDateTime方法来设置时间。运行上述代码,会输出设置的时间,例如:`设置的时间为:Tue Aug 31 14:30:00 CST 2021`。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)