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);
Joda-Time is the most widely used date and time processing library, before the release of Java 8. Its purpose was to offer an intuitive API for processing date and time and also address the design issues that existed in the Java Date/Time API.
Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.
How to change the SimpleDateFormat to jodatime? String s = "2014-01-15T14:23:50.026"; DateTimeFormatter dtf = DateTimeFormat. forPattern("yyyy-MM-dd'T'HH:mm:ss. SSSS"); DateTime instant = dtf.
Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.
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)."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With