This 0ne Pr0grammer This 0ne Pr0grammer - 11 months ago 49
Java Question

Best Way to Set Day to the First of the Month Using DateTime Without Inherent WithDayOfMonth Method

So, I'm trying to basically take 2 DateTime objects and set them to the first day of their respective months so that I can ultimately calculate the months between the two dates.

Example of the code:

DateTime dt = new DateTime();
DateTime newDT = dt.withDayOfMonth(1);

And before anyone asks, the actual code coverts a Date object into a DateTime object which is used in another section of the code.

The issue is, when I do this in a unit test it seems to work just fine. However, when I try to test this using SOAP UI I can see in the course of debugging that I'm getting a runtime exception due to:

method lookup failed for selector "withDayOfMonth" with signature "(I)Lorg/joda/time/DateTime;"

In the corresponding server.txt log file, I can see a stack trace which indicates a no such method has occured.

After further research, I've found that our app server currently employs an outdated version of the JodaTime jar (1.2.1), while my eclipse library contains the correct jar (1.6.2).

However, now the question becomes what's the best way to accomplish my goal here (to create a new DateTime object with the first day of the month set to 0) since I don't have access to the withDayOfMonth method provided by JodaTime?

Answer Source

A possible way to do so, using another method for Joda-Time API which is present in 1.2.1 version it's the follow:

DateTime dateTime = new DateTime().dayOfMonth().withMinimumValue();

Another approach could be to use jdk Calendar to set the first day of the month for a date. And then get the joda DateTime using DateTime(Calendar cal) constructor:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1); 
DateTime dateTime = new DateTime(cal);

However probably as other answer suggest the best you can do is update your Joda-Time version.