编写j一个java程序实现日期和时间处理
时间: 2023-07-15 10:15:09 浏览: 122
以下是一个简单的Java程序,用于获取当前日期和时间,以及执行一些基本的日期和时间操作:
```java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeExample {
public static void main(String[] args) {
// 获取当前日期和时间
LocalDate currentDate = LocalDate.now();
LocalTime currentTime = LocalTime.now();
LocalDateTime currentDateTime = LocalDateTime.now();
// 打印当前日期和时间
System.out.println("Current Date: " + currentDate);
System.out.println("Current Time: " + currentTime);
System.out.println("Current Date and Time: " + currentDateTime);
// 格式化日期和时间
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
String formattedDate = currentDate.format(dateFormatter);
String formattedTime = currentTime.format(timeFormatter);
String formattedDateTime = currentDateTime.format(dateTimeFormatter);
// 打印格式化后的日期和时间
System.out.println("Formatted Date: " + formattedDate);
System.out.println("Formatted Time: " + formattedTime);
System.out.println("Formatted Date and Time: " + formattedDateTime);
// 执行日期和时间操作
LocalDate tomorrow = currentDate.plusDays(1);
LocalDate lastWeek = currentDate.minusWeeks(1);
LocalTime twoHoursLater = currentTime.plusHours(2);
// 打印执行操作后的日期和时间
System.out.println("Tomorrow's Date: " + tomorrow);
System.out.println("Last Week's Date: " + lastWeek);
System.out.println("Two Hours Later: " + twoHoursLater);
}
}
```
此程序使用Java 8的日期和时间API。它获取当前日期和时间,并使用格式化程序将其格式化为指定的格式。它还执行一些基本的日期和时间操作,例如添加一天,减去一周,以及添加两个小时。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)