I'm a beginner and i want to add the time from a variable to another time variable. Both of them have as type java.util.Date .I thought, it's possible to add by calling the Method getTime() getTime(); But i get not the correct result. Can anyone help me please? pd => Thu Jan 01 11:10:37 CET 1970 parsedDate => Thu Jan 01 02:00:00 CET 1970
long timeValue= pd.getTime() parsedDate.getTime();
int hValue=(int) TimeUnit.MILLISECONDS.toHours(timeValue);
int mValue=(int) TimeUnit.MILLISECONDS.toMinutes(timeValue)`;
int sValue=(int) TimeUnit.MILLISECONDS.toSeconds(timeValue)`;
result (after i get only the time): 11:10:37
CodePudding user response:
I'd like to suggest using other java date objects if your java version allows it.
For example Calendar:
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
//How to obtain integers for doing manual calculations
int hour = calendar.get(Calendar.HOUR); // 12 hour clock
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
LocalDate, another data type, provides nice methods like for example plusMonths(month).
CodePudding user response:
java.time
I recommend that you use java.time, the modern Java date and time API, for your time work. If 11:10:37 is a time of day and 02:00:00 is a duration to add to it, use LocalTime
and Duration
for them.
LocalTime start = LocalTime.of(11, 10, 37);
Duration timeToAdd = Duration.ofHours(2);
LocalTime end = start.plus(timeToAdd);
System.out.println(end);
Output:
13:10:37
If both are amounts of time, use two Duration
objects and add them together using the plus
method of Duration
.
The Date
class that no one should be using any more was used for a point in time, a moment, in your case a moment in 1970. That class was never meant nor suitable for an amount of time. So it makes no sense to try to add two of them together.
CodePudding user response:
Thank you all but i already solved the problem by using LocalTime:
SimpleDateFormat form = new SimpleDateFormat("HH:mm:ss");
pd = form.parse(s);
LocalTime pdTime= LocalTime.of(pd.getHours(), pd.getMinutes(), pd.getSeconds());
LocalTime updatedTime = pdTime.plusHours(parsedDate.getHours()).plusMinutes(parsedDate.getMinutes()).plusSeconds(parsedDate.getSeconds());