Java 中 LocalTime 转 Date 的方法
要将 'LocalTime' 转换为 'Date',可以使用以下方法:
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = localTime.atDate(LocalDate.now());
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
在这个例子中,我们首先使用 'LocalTime.now()' 获取当前的 'LocalTime'。然后,我们使用 'atDate(LocalDate.now())' 方法将 'LocalTime' 与当前日期('LocalDate.now()')组合为 'LocalDateTime'。接下来,我们使用 'atZone(ZoneId.systemDefault()).toInstant()' 将 'LocalDateTime' 转换为 'Instant',然后使用 'Date.from()' 方法将 'Instant' 转换为 'Date'。
请注意,'Date' 是一个不可变的对象,而 'LocalTime' 是一个可变的对象。因此,转换后的 'Date' 对象将只包含时间部分,日期部分将被设置为当前日期。
请注意,这种转换可能会导致时区的问题。在上述示例中,我们使用 'ZoneId.systemDefault()' 获取系统默认时区。如果需要,您可以更改为特定的时区。
原文地址: https://www.cveoy.top/t/topic/pqRf 著作权归作者所有。请勿转载和采集!