Reputation: 1005
I'm looking to update the time for DateTime
object. I've noticed that there are two different methods for creating a copy of a DateTime
object with an updated time, but I'm not sure which to use.
Is there an advantage of using one of these over the other?
import org.joda.time.DateTime;
DateTime oldTime = DateTime.now()
newTime = oldTime.withMinuteOfHour(30)
versus
import org.joda.time.DateTime;
DateTime oldTime = DateTime.now()
newTime = oldTime.minuteOfHour.setCopy(30)
Upvotes: 0
Views: 180
Reputation: 213233
Talking about performance - I don't really bother much, because those 3 lines is almost never going to be a bottleneck in your application unless you're dealing an extreme memory intensive application, where a single extra object might be much of a deal. (Just so you know, I went to the source code, and found out, second approach created an extra Property
object)
Talking about readibility - certainly I would go with 1st one. Because I've to go to the API to see what setCopy()
does. First one clearly shows the intent, that it is request a new DateTime
object, with minuteOfHour
set to the passed value.
Here's another reason why I would not prefer the 2nd approach. The minuteOfHour()
method returns a Property
:
Property minuteOfHour = date.minuteOfHour();
Now that property can be assigned to any property of date
. I can later on do:
minuteOfHour = date.dayOfYear();
That would compile, but changes the meaning of variable without actually changing the name. That means, you won't really know what property you're setting to when you call: Property#setCopy()
.
Upvotes: 2
Reputation: 1905
They are probably about the same - here is the source code for withMinuteOfHour -
public DateTime withMinuteOfHour(int minute) {
return withMillis(getChronology().minuteOfHour().set(getMillis(), minute));
}
While minuteOfHour is -
public Property minuteOfHour() {
return new Property(this, getChronology().minuteOfHour());
}
So the core of the calls are the same
Upvotes: 1