Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify date without modifying time

Tags:

java

jodatime

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

like image 974
Mike Baxter Avatar asked Oct 11 '13 10:10

Mike Baxter


2 Answers

Is JodaTime a must? Basic way to do this is 1. extract just time from timestamp. 2. add this to just date


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 this.

like image 165
Denis Avatar answered Oct 14 '22 23:10

Denis


Previously accepted answer were removed by moderator, as it contains only link to javadoc. Here is edited version.


You could do it like this

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

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

like image 22
Admit Avatar answered Oct 14 '22 23:10

Admit