Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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"));
    Instant instant = currentTime.toInstant(ZoneOffset.UTC);
    Date currentDate = Date.from(instant);
    System.out.println("Current Date = " + currentDate);
    currentTime.plusHours(12);
    Instant instant2 = currentTime.toInstant(ZoneOffset.UTC);
    Date expiryDate = Date.from(instant2);
    System.out.println("After 12 Hours = " + expiryDate);

"Current Date" Time is showing Same as "After 12 Hours"...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...