Change date without changing time

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

My first attempt was to store the "temporary" parts of DateTime in a separate int using getHoursOfDay() and getMinutesOfHour() , etc. - then create a new DateTime with the desired date and set the hours, minutes and seconds back. But this method is pretty awkward, and I was wondering if there was a less complicated method for this - ideally with just one line of code.

For instance:

22/05/2013 13:40:02 β†’ β†’ 30/08/2014 13:40:02

+6
source share
3 answers

The previously accepted answer was deleted by the moderator, as it contains only a link to javadoc. The version is edited here.


You can do it like this:

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

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

+1
source

Is JodaTime required? The main way to do this is 1. retrieve only time from the timestamp. 2. Add this to the date only.

 long timestamp = System.currentTimeMillis(); //OK we have some timestamp long justTime = timestamp % 1000 * 60 * 60 * 24;// just tiem contains just time part long newTimestamp = getDateFromSomeSource();//now we have date from some source justNewDate = newTimestamp - (newTimestamp % 1000 * 60 * 60 * 24);//extract just date result = justNewDate + justTime; 

Something like that.

+2
source

Use withFields follows:

 new DateTime().withFields(new LocalDate(2000,1,1)) 

In this case, all DateTime time-field fields will be set for those contained in LocalDate - year, month, and day. This will work with any implementation of ReadablePartial , such as YearMonth .

+1
source

Source: https://habr.com/ru/post/955756/


All Articles