有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从瞬间和时间字符串构造ZoneDateTime?

给定一个对象Instant,一个time string表示特定ZoneId的时间,如何构造一个ZonedDateTime对象,其中日期部分(年、月、日)是从给定ZoneId的瞬间开始的,时间部分是从给定time string开始的

例如:

给定一个即时值对象143740400000(相当于20-07-2015 15:00 UTC),一个时间字符串21:00,以及一个表示欧洲/伦敦ZoneId对象,我想构造一个ZonedDateTime对象,相当于20-07-2015 21:00欧洲/伦敦


共 (2) 个答案

  1. # 1 楼答案

    首先要将时间字符串解析为LocalTime,然后可以使用区域从Instant调整ZonedDateTime,然后应用时间。例如:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm", Locale.US");
    LocalTime time = LocalTime.parse(timeText, formatter);
    ZonedDateTime zoned = instant.atZone(zoneId)
                                 .with(time);
    
  2. # 2 楼答案

    创建瞬间并确定该瞬间的UTC日期:

    Instant instant = Instant.ofEpochMilli(1437404400000L);
    LocalDate date = instant.atZone(ZoneOffset.UTC).toLocalDate();
    
    // or if you want the date in the time zone at that instant:
    
    ZoneId tz = ZoneId.of("Europe/London");
    LocalDate date = instant.atZone(tz).toLocalDate();
    

    解析时间:

    LocalTime time = LocalTime.parse("21:00");
    

    从所需ZoneId的LocalDate和LocalTime创建ZoneDateTime:

    ZonedDateTime zdt = ZonedDateTime.of(date, time, tz);
    

    正如Jon所指出的,您需要决定您想要的UTC日期可能与当时给定时区的日期不同