Java8 Adding Hours To LocalDateTime Not Working

前端 未结 2 1774
深忆病人
深忆病人 2021-02-18 12:51

I tried like below, but in both the cases it is showing same time? What i am doing wrong.

    LocalDateTime currentTime = LocalDateTime.now(ZoneId.of(\"UTC\"));
         


        
2条回答
  •  礼貌的吻别
    2021-02-18 13:28

    The documentation of LocalDateTime specifies the instance of LocalDateTime is immutable, for example plusHours

    public LocalDateTime plusHours(long hours)

    Returns a copy of this LocalDateTime with the specified number of hours added.

    This instance is immutable and unaffected by this method call.

    Parameters:
    hours - the hours to add, may be negative
    Returns:
    a LocalDateTime based on this date-time with the hours added, not null
    Throws:
    DateTimeException - if the result exceeds the supported date range

    So, you create a new instance of LocalDateTime when you execute plus operation, you need to assign this value as follows:

    LocalDateTime nextTime = currentTime.plusHours(12);
    Instant instant2 = nextTime.toInstant(ZoneOffset.UTC);
    Date expiryDate = Date.from(instant2);
    System.out.println("After 12 Hours = " + expiryDate);
    

    I hope it can be helpful for you.

提交回复
热议问题