How to convert a LocalDate to an Instant?

前端 未结 2 569
轮回少年
轮回少年 2021-01-30 15:14

I work with the new DateTime API of Java 8.

How to convert a LocalDate to an Instant? I get an exception with

LocalDate date = LocalDate.of(2012, 2, 2);
         


        
2条回答
  •  迷失自我
    2021-01-30 16:03

    The Instant class represents an instantaneous point on the time-line. Conversion to and from a LocalDate requires a time-zone. Unlike some other date and time libraries, JSR-310 will not select the time-zone for you automatically, so you must provide it.

    LocalDate date = LocalDate.now();
    Instant instant = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
    

    This example uses the default time-zone of the JVM - ZoneId.systemDefault() - to perform the conversion. See here for a longer answer to a related question.


    Update: The accepted answer uses LocalDateTime::toInstant(ZoneOffset) which only accepts ZoneOffset. This answer uses LocalDate::atStartOfDay(ZoneId) which accepts any ZoneId. As such, this answer is generally more useful (and probably should be the accepted one).

    PS. I was the main author of the API

提交回复
热议问题