Vikram
Vikram

Reputation: 7517

How to set Time property in Java using Joda-Time

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);

Upvotes: 30

Views: 39280

Answers (2)

John Kugelman
John Kugelman

Reputation: 361546

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)."

Upvotes: 75

Edwin Buck
Edwin Buck

Reputation: 70909

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.

Upvotes: 3

Related Questions