可以使用Java8中的LocalDateTime类 直接获取年月
时间: 2023-10-14 09:22:17 浏览: 42
日信息。
例如,获取当前时间的年月日信息可以使用以下代码:
```
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
```
其中,`getYear()`方法获取当前时间的年份,`getMonthValue()`方法获取当前时间的月份(返回值为1~12),`getDayOfMonth()`方法获取当前时间的日(返回值为1~31)。
如果需要指定一个特定的时间,可以使用`LocalDateTime.of()`方法创建一个指定时间的`LocalDateTime`对象,例如:
```
LocalDateTime dateTime = LocalDateTime.of(2022, 3, 15, 10, 30);
int year = dateTime.getYear(); // 2022
int month = dateTime.getMonthValue(); // 3
int day = dateTime.getDayOfMonth(); // 15
```
其中,`LocalDateTime.of()`方法的参数依次为年、月、日、时、分、秒。
相关问题
LocalDateTime获取当前年月
`LocalDateTime` 是 Java 8 中的一个日期和时间类,它表示没有时区信息的日期和时间。如果你想获取当前的年份和月份,你可以使用 `now()` 方法结合 `MonthOfYear` 枚举来实现。以下是一个示例:
```java
import java.time.LocalDateTime;
import java.time.MonthOfYear;
// 获取当前日期和时间(包括年月)
LocalDateTime currentDate = LocalDateTime.now();
// 提取年份和月份
int currentYear = currentDate.year();
MonthOfYear currentMonth = currentDate.getMonth();
System.out.println("当前年份: " + currentYear);
System.out.println("当前月份: " + currentMonth);
LocalDateTime 获取当前时间 年月日时分秒
好的,使用 Java 8 的 LocalDateTime 类可以获取当前时间的年月日时分秒。以下是示例代码:
```java
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
System.out.printf("当前时间:%d年%d月%d日 %d时%d分%d秒", year, month, day, hour, minute, second);
}
}
```
输出结果类似于:
```
当前时间:2021年9月7日 15时37分29秒
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.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)