Reputation: 7268
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 int
s 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
Upvotes: 6
Views: 537
Reputation: 4987
You could do it like this
DateTime myDate = ...
myDate.withDate(desiredYear, desiredMonth, desiredDayOfMonth);
JavaDoc is here: DateTime.withDate(int year, int month, int dayOfMonth)
Upvotes: 1
Reputation: 13556
use withFields like this:
new DateTime().withFields(new LocalDate(2000,1,1))
This will set all date time fields of the DateTime
to those that are contained in the LocalDate
- year, month and day in this case. This will work with any ReadablePartial
implementation like YearMonth
for example.
Upvotes: 1
Reputation: 1273
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.
Upvotes: 2