2023-02-01 如何转Calendar
时间: 2023-12-02 14:03:56 浏览: 35
可以通过以下步骤将 `LocalDate` 转换为 `Calendar`:
1. 使用 `LocalDate.atStartOfDay(ZoneId zone)` 方法将 `LocalDate` 转换为 `ZonedDateTime` 对象;
2. 调用 `ZonedDateTime.toInstant()` 方法将 `ZonedDateTime` 转换为 `Instant` 对象;
3. 使用 `Date.from(Instant instant)` 方法将 `Instant` 转换为 `Date` 对象;
4. 使用 `Calendar.getInstance()` 方法获取一个 `Calendar` 对象,并将其设置为转换得到的 `Date` 对象。
以下是一个示例代码,用于将 `LocalDate` 对象 `2023-02-01` 转换为 `Calendar` 对象:
```java
LocalDate localDate = LocalDate.of(2023, 2, 1);
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
Instant instant = zonedDateTime.toInstant();
Date date = Date.from(instant);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println(calendar.getTime()); // 输出:Thu Feb 01 00:00:00 CST 2023
```
在上述代码中,首先创建了一个 `LocalDate` 对象 `localDate`,表示日期为2023年2月1日。然后使用 `atStartOfDay(ZoneId zone)` 方法将其转换为 `ZonedDateTime` 对象,使用 `toInstant()` 方法将其转换为 `Instant` 对象,使用 `from(Instant instant)` 方法将其转换为 `Date` 对象。最后使用 `Calendar.getInstance()` 方法获取一个 `Calendar` 对象,并将其设置为转换得到的 `Date` 对象。最终输出 `Calendar` 对象对应的日期,输出结果为 `Thu Feb 01 00:00:00 CST 2023`。