取localdatetime对象的年月日作为localdatetime属性
时间: 2023-12-27 13:22:39 浏览: 37
可以使用LocalDate类的of()方法创建一个新的LocalDate对象,然后将其与LocalTime对象组合成一个LocalDateTime对象。以下是一个示例代码:
```java
LocalDate date = LocalDate.of(2021, 10, 1);
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.of(date, time);
```
这将创建一个LocalDateTime对象,其日期部分为2021年10月1日,时间部分为当前时间。你可以根据需要更改日期部分的值,例如:
```java
LocalDate date = LocalDate.of(2022, 1, 1);
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.of(date, time);
```
这将创建一个LocalDateTime对象,其日期部分为2022年1月1日,时间部分为当前时间。
相关问题
LocalDateTime取年月日
以下是使用LocalDateTime获取年月日的方法:
```java
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.now();
int year = localDateTime.getYear();
int month = localDateTime.getMonthValue();
int day = localDateTime.getDayOfMonth();
System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Day: " + day);
}
}
```
输出结果:
```
Year: 2021
Month: 10
Day: 20
```
LocalDateTime 输出年月日
以下是使用LocalDateTime输出年月日的示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = now.format(formatter);
System.out.println("年月日: " + formattedDate);
}
}
```
输出结果为:
```
年月日: 2022-01-01
```