Java程序将java.util.Date转换为特定时区中的任何本地日期
首先,设置Date和ZoneId-
Date date = new Date(); ZoneId zone = ZoneId.systemDefault();
现在将java.util.date转换为localdate-
date.toInstant().atZone(zone).toLocalDate() date.toInstant().atZone(zone).toLocalTime() date.toInstant().atZone(zone).getHour() date.toInstant().atZone(zone).getMinute() date.toInstant().atZone(zone).getSecond()
示例
import java.time.ZoneId; import java.util.Date; public class Demo { public static void main(String[] args) { Date date = new Date(); ZoneId zone = ZoneId.systemDefault(); System.out.println("LocalDate = "+date.toInstant().atZone(zone).toLocalDate()); System.out.println("LocalTime= "+date.toInstant().atZone(zone).toLocalTime()); System.out.println("Hour = "+date.toInstant().atZone(zone).getHour()); System.out.println("Minute = "+date.toInstant().atZone(zone).getMinute()); System.out.println("Seconds = "+date.toInstant().atZone(zone).getSecond()); } }
输出结果
LocalDate = 2019-04-18 LocalTime= 23:25:09.708 Hour = 23 Minute = 25 Seconds = 9