30

I want to set the hour, minute and seconds in Joda-Time. But when I set it's not changing the property.

Here is my code:

import org.joda.time.DateTime;
public class JodaAkbar 
{
 public static void main(String args[])
 { 
    DateTime dt = new DateTime();
    System.out.println("Before:"+dt);
    dt.hourOfDay().setCopy(5);
    dt.minuteOfDay().setCopy(20);
    dt.secondOfDay().setCopy(0);
    System.out.println("After:"+dt);
 }
}

Here is the output.

Before:2015-04-01T11:01:38.277+11:00
After:2015-04-01T11:01:38.277+11:00

I am getting the same output. What's happening wrong here?

EDIT:

Basically, I want to do something similar as shown in the below code. As the below code doesn't work properly for 24 hour format, I switched to Joda-Time.

 Calendar cal = Calendar.getInstance();
 cal.set(Calendar.HOUR, 13);
 cal.set(Calendar.MINUTE, 25);
 cal.set(Calendar.SECOND, 0);
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
vkrams
  • 7,267
  • 17
  • 79
  • 129
  • AKAIK `DateTime` is immutable, it can't be changed in of it self, but `setCopy` will return a new instance of `DateTime` with the update values. `DateTime after = dt.houtOfDay().setCopy(5)`... – MadProgrammer Apr 01 '15 at 00:13

2 Answers2

75

Joda-Time objects are immutable. The word "copy" in setCopy is telling you that it doesn't set these fields directly, but instead creates a copy of the DateTime with that field modified.

A quick fix is:

dt = dt.hourOfDay().setCopy(5);
dt = dt.minuteOfHour().setCopy(20);
dt = dt.secondOfMinute().setCopy(0);

A more fluent approach would be to chain several with methods together:

DateTime dt = new DateTime()
    .withHourOfDay(5)
    .withMinuteOfHour(20)
    .withSecondOfMinute(0);

Or do it all with a single withTime call:

DateTime dt = new DateTime().withTime(5, 20, 0, 0);

By the way, Java 8 introduces a new java.time package which was inspired by Joda-Time. The Joda-Time web site recommends, "From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310)."

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
3

Look into immutable data structures. The modifiers on a JodaTime object don't really modify the object, but return different instances constructed from the original object with the desired field set as requested.

So, in effect, you're constructing a lot of items, and not assigning them to anything, so they're getting garbage collected. Finally, you're printing out the same (immutable) item twice.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138