Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

How do you get a Joda DateTime out of a localDate with is defaulted to Midnight? This is the common case of I have a date, but I need to have a time on it now and that time would be midnight.

LocalDate localDate = new LocalDate();
localDate.toDateTimeAtStartOfDay();

February 13th, 2014

Posted In: Java, Joda-Time

Leave a Comment

If you JVM is showing the wrong time, it may be because it is picking up the wrong timezone. Specify the following to fix it:

-Duser.timezone=”America/Louisville”

September 12th, 2012

Posted In: Java, Joda-Time

Tags: , ,

Leave a Comment

I was tasked with comparing one date to another to see which one was greater. To compound the issue. They can be in different timezones. I tried to change the timezone of the DateTime object, but nothing happened. This is because Joda DateTime object are immutable. Doh. I needed a MutableDateTime object. I ended up with:

        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("MM/dd/yyyy");
        DateTime dateTime = dateTimeFormatter.parseDateTime(dateString);
        MutableDateTime mutableDateTime = dateTime.toMutableDateTime();
        mutableDateTime.setZone(DateTimeZone.forID("America/Los_Angeles"));

Note that when a DateTime object is created, it takes the timezone from the system that created it. When you change the timezone, the offset value will change and the time is adjusted. If the offset changes by two hours, the time will change by two hours.

January 10th, 2012

Posted In: Java, Joda-Time

Leave a Comment

To parse a string into a DateTime object:

DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime dt = fmt.parseDateTime(strInputDateTime);

To output the formatted value of a DateTime object as a String:

fmt.print(myDateTime)

January 11th, 2011

Posted In: Collections, Java, Joda-Time

Leave a Comment

LinkedIn Auto Publish Powered By : XYZScripts.com