Reputation: 6363
Is there any way to update only a Date's time path?
I tried Date.setTime()
but it replaces the date path too. I there any java method or the only way is to set hour, minute, second and milisecond?
Thank you
Upvotes: 0
Views: 113
Reputation: 234817
A Java Date
is just a wrapper around a long
that counts time from the epoch (January 1, 1970). Much more flexible is Calendar
. You can create a Calendar
from a Date
:
Date date = . . .;
Calendar cal = new GregorianCalendar();
cal.setTime(date);
Then you can set various fields of the Calendar
:
cal.set(Calendar.HOUR_OF_DAY, 8);
// etc.
Upvotes: 4
Reputation: 347284
You'll want to take a look at java.util.Calender.
It will allow you to change the individual parts of the date/time.
Calendar cal = Calender.getInstance();
cal.setTime(date);
cal.set(Calender.HOUR, hour);
Alternatively, as has already being suggested, I'd take a look at Joda Time
Upvotes: 1
Reputation: 1501163
I would start by moving away from java.util.Date
entirely. Ideally, use Joda Time as it's a far more capable date/time library.
Otherwise, you should use java.util.Calendar
. A java.util.Date
doesn't have a particular date/time until you decide what time zone you're interested in - it just represents an instant in time, which different people around the world will consider to be a different date and time of day.
Upvotes: 3