旮旯轩

集中精力,下定决心,永不放弃
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java Instant\Date\LocalDateTime\Calendar\ZonedDateTime转化

Posted on 2022-06-27 16:06  在下刚哥  阅读(199)  评论(0编辑  收藏  举报
public static Instant toInstant(Date date) {
return Instant.ofEpochMilli(date.getTime());
}

public static Date toDate(Instant instant) {
return new Date(instant.toEpochMilli());
}

public static Date toDate(LocalDateTime ldt) {
return new Date(ldt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
}

public static Calendar toCalendar(ZonedDateTime zdt) {
TimeZone tz = TimeZone.getTimeZone(zdt.getZone());
Calendar calendar = Calendar.getInstance(tz);
calendar.setTimeInMillis(zdt.toInstant().toEpochMilli());
return calendar;
}


public static LocalDateTime toLocalDateTime(Date date) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
}


public static ZonedDateTime toZonedDateTime(Calendar calendar) {
ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(calendar.getTimeInMillis()), calendar.getTimeZone().toZoneId());
return zdt;
}