12-2 日期与时间类的简单应用
时间: 2024-03-26 19:41:12 浏览: 26
Java中提供了日期与时间类Date、Calendar和DateFormat。其中Date类表示一个特定的时间点,Calendar类提供了丰富的操作方法来处理日期和时间,DateFormat类则可以将日期和时间转换为字符串。
下面是一个简单的日期与时间类的应用示例:
```java
import java.util.*;
public class DateTimeExample {
public static void main(String[] args) {
// 获取当前日期和时间
Date now = new Date();
System.out.println("当前时间: " + now);
// 使用Calendar类获取当前日期和时间
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
System.out.println("当前日期: " + year + "-" + month + "-" + day);
System.out.println("当前时间: " + hour + ":" + minute + ":" + second);
// 使用DateFormat类将日期和时间转换为字符串
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nowStr = dateFormat.format(now);
System.out.println("当前时间: " + nowStr);
}
}
```
运行上述代码,可以得到如下输出结果:
```
当前时间: Fri Oct 22 16:18:26 CST 2021
当前日期: 2021-10-22
当前时间: 16:18:26
当前时间: 2021-10-22 16:18:26
```
上述代码中,我们首先使用Date类获取当前日期和时间,然后使用Calendar类获取当前日期和时间,并将其分别输出。最后,我们使用DateFormat类将日期和时间格式化为字符串,并输出。