Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to clone java.time.LocalDateTime

I would like to create a copy java.time.LocalDateTime but it does not have clone() method.

What I do is the following:

long epochMilli = Instant.now().toEpochMilli();  LocalDateTime createDate =  LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneId.systemDefault());  LocalDateTime modificationDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMilli), ZoneId.systemDefault()); 

Is there an easyest way to create two LocalDateTime objects with the exact same date-time value?

like image 595
zappee Avatar asked Aug 14 '18 13:08

zappee


People also ask

How do I get time difference in LocalDateTime?

getDays() + " days " + time[0] + " hours " + time[1] + " minutes " + time[2] + " seconds.");

Is LocalDateTime immutable?

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision.

Should I use LocalDateTime or instant?

Instant and LocalDateTime are two entirely different animals: One represents a moment, the other does not. Instant represents a moment, a specific point in the timeline. LocalDateTime represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment.


2 Answers

Because LocalDateTime is immutable, you can simply reference the same object:

LocalDateTime createDate = LocalDateTime.now();  LocalDateTime modificationDate = createDate; 
like image 105
Jacob G. Avatar answered Sep 30 '22 19:09

Jacob G.


Since it's immutable, you can do it this way:

LocalDateTime copy = createDate.plusHours(0); System.out.println(createDate.equals(copy)); // true 

plusHours doc:

Returns a copy of this LocalDateTime with the specified number of hours added. This instance is immutable and unaffected by this method call.

like image 43
xingbin Avatar answered Sep 30 '22 20:09

xingbin