Search code examples
javajodatime

Modify date without modifying time


With JodaTime, without using the 'plus' or 'minus' functions and using the least lines of code, how can I set a new date without modifying the time?

My first attempt was to store the 'time' parts of the DateTime in separate ints using getHoursOfDay() and getMinutesOfHour() etc - then create a new DateTime with the required date and set the hours, minutes, and seconds back again. But this method is pretty clunky, and I was wondering if there was a less verbose method for doing this - ideally with just one line of code.

For example:

22/05/2013 13:40:02 >>>> 30/08/2014 13:40:02


Solution

  • You could do it like this

    DateTime myDate = ...
    myDate.withDate(desiredYear, desiredMonth, desiredDayOfMonth);
    

    JavaDoc is here: DateTime.withDate(int year, int month, int dayOfMonth)