Reputation: 342
sample code for adding:
String time1="0:01:30";
String time2="0:01:35";//For temp Only
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date date1 = timeFormat.parse(time1);
Date date2 = new Date();//timeFormat.parse(time2);
String s = timeFormat.format(date2);
Date date4 = timeFormat.parse(s);
long sum = date1.getTime() + date4.getTime();
String date3 = timeFormat.format(new Date(sum));
System.out.println("The sum is "+date3);// output not getting correctly
sample Code for subtration:
calculationBetween2Dates(Date bigTime, Date smallTime){
SimpleDateFormat st1 = new SimpleDateFormat("HH:mm");
long diff = bigTime.getTime() - smallTime.getTime();
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long onlyMinits = diffMinutes - (diffHours * 60);
String var = String.valueOf(diffHours + ":" + onlyMinits);
Date warkedDate = st1.parse(var);
return warkedDate;
}// it worked For me for sub between 2 timings
Doing adding was not possible; what's wrong in my adding code?
Upvotes: 1
Views: 987
Reputation: 103817
Java Date
objects, are wrappers around a specific point in time. This is implemented as "the number of milliseconds past the epoch [1 Jan 1970]". And, as per the Javadocs, the getTime()
method returns this number of milliseconds.
So, when you parse your time into a Date
, you're not getting an object that represents "1:30am". You're getting an object that represents "1:30am today". And so its getTime() will return some number that represents about 45 years in milliseconds.
If you add two of these outputs together, you'll get a number that is about 90 years in milliseconds, and so if you turn it back into a Date
you'll get an instant that represents some point in late 2059. That is... really not what you want.
(Note that it sort of works for the subtraction case, because you get two very large numbers that are nevertheless just a half hour apart. When you subtract them, you're left with a date that represents a little after midnight on 1 Jan 1970. Still - this might not work in some edge cases, depending on things like daylight savings times, because you're still referencing actual instants in history - so I wouldn't rely on it.)
The better way to do it, is by using an object that represents just a time-of-day. Java 8 has LocalTime
to represent this, and you could easily add two of these by combining the result of the toSecondOfDay
call.
Edit: If you're stuck using an earlier version of Java... The standard response for any date/time related questions used to be "use Joda-Time" (which is what the Java 8 classes were based on anyway). If third-party libraries aren't an option for whatever reason, then you'll probably have to implement your own class to represent and add times (it's not that involved - just three int fields, and some logic to "carry the one" when the latter two hit 60).
Upvotes: 4