The classical way to calculate the difference between two dates in Java is to:
- parse them to
Date
objects
- convert both of them to "milliseconds since the UNIX epoch" by calling
Date.getTime()
- subtract one from the other.
- divide by a constant to convert from milliseconds to the time unit that you require.
Your code seems to be doing that but there are a couple of problems:
- the constant is wrong
- you are truncating to an
int
which is liable to give you errors if the two dates are far enough apart.
This would be better:
public long hoursDifference(Date start, Date end) {
return ((end.getTime() - start.getTime()) / (1000 * 60 * 60));
}
Also, you might want to consider rounding rather than truncation.
Parsing dates in an arbitrary format is impossible ... unless you know a priori what the expected format or formats are. In that case, you just try the formats, one at a time, until your parse succeeds. For example, something like this.
SimpleDateFormat[] sdf = new SimpleDateFormat[] {
new SimpleDateFormat(/* format 1 */),
new SimpleDateFormat(/* format 2 */),
...
};
...
Date date = null;
for (int i = 0; i < sdf.length && date == null; i++) {
try {
date = sdf[i].parse(dateString);
} catch (ParseException ex) { /* */ }
}
if (date == null) {
/* report parse error ... */
}
But beware, you won't be able to handle every possible date format correctly. For example, you won't be able to distinguish 7/6/2000 (English 7th of June 2000) from 7/6/2000 (American 6th of July 2000).
IMO, you are better off giving the user a Date chooser of some kind.
... but i want Dataformat is like this yyyy-mm-dd hh:mm:ss
The date format strings are documented in the javadocs for SimpleDateFormat
. Read the documentation and you will be able to work it out. And you will be able to work out how to parse other formats too!