Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the direct way to copy a joda LocalTime?

Tags:

java

jodatime

I want a new instance that is a copy. I could instantiate from integers but it seems there should be a more direct way. I could also use some sort of approach like copy = original.minus(zero) but that is also indirect.

The LocalTime constructor that accepts a Java Object argument (for which I used the original LocalTime) does not work. I guess it just does not support it.

        LocalTime start = new LocalTime(9, 0, 0);
        LocalTime stop = new LocalTime(17, 0, 0);

        //LocalTime time = start.minusSeconds(0);  // GOOD VERSION
        LocalTime time = new LocalTime(start);     // THE BAD VERSION

        assert time == start: "does not work";

        // EXTRANEOUS STUFF TO JUSTIFY COPYING AN IMMUTABLE, FOLLOWS...
        while (time.compareTo(stop) <= 0)
        {
            //method(time, new LocalTime(9, 0, 0), stop); // MESSY
            method(time, start, stop);                    // NICER
            time = time.plusMinutes(1);
        }

I also tried copy = new LocalTime(original.getLocalMillis()) but I do not have access to getLocalMillis as it is protected.

like image 940
H2ONaCl Avatar asked Feb 25 '23 04:02

H2ONaCl


1 Answers

LocalTime is immutable, so there is no point holding on to 2 instances with the same value. They can be shared (even across threads). The mutation methods, e.g. plus/minus will return a new value, so you can create your copy "on demand" when you need the modified value.

LocalTime start = new LocalTime(9, 0, 0);
LocalTime stop = new LocalTime(17, 0, 0);
LocalTime time = start;     // Just use the reference

while (time.compareTo(stop) <= 0)
{
    method(time, start, stop);
    time = time.plusMinutes(1);
}
like image 60
Michael Barker Avatar answered Feb 26 '23 20:02

Michael Barker