Java8 java.util.Date conversion to java.time.ZonedDateTime

Java8 java.util.Date conversion to java.time.ZonedDateTime

Asked on December 28, 2018 in Java.
Add Comment


  • 4 Answer(s)

    The ZonedDateTime gives us the method called ZonedDateTime.ofInstant(Instant, ZoneId). which is used to transform an Instant to a ZonedDateTime,

    There for if we want ZonedDateTime in the default timezone, The code will be like this.

    ZonedDateTime d = ZonedDateTime.ofInstant(calculateFromDate.toInstant(),
    ZoneId.systemDefault());
    
    Answered on December 28, 2018.
    Add Comment

    For ZonedDateTime , we can use this code given below.

    calculateFromDate.toInstant().atZone(ZoneId.systemDefault())
    
    

    If we really need a LocalDate call the toLocalDate method .For more reference  Convert java.util.Date to java.time.LocalDate.

    Answered on December 28, 2018.
    Add Comment

    To obtain a ZonedDateTime from a Date you can use:

    calculateFromDate.toInstant().atZone(ZoneId.systemDefault())

    You can then call the toLocalDatemethod if you need a LocalDate.

    Answered on January 16, 2019.
    Add Comment
    import java.time.ZoneId;
    import java.time.ZonedDateTime;
    import java.util.Date;
    //ww w .  j  av  a2 s.  c  o  m
    public class Main {
    
      public static void main(String[] args) {
    
        System.out.println(toZonedDateTime(new Date()));
      }
    
      public static ZonedDateTime toZonedDateTime(Date utilDate) {
        if (utilDate == null) {
          return null;
        }
        final ZoneId systemDefault = ZoneId.systemDefault();
        return ZonedDateTime.ofInstant(utilDate.toInstant(), systemDefault);
      }
    }
    Answered on January 16, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.