I am new to Java and trying some practice exercises to get a better understanding of it.
I set myself the exercise to input different Strings, integers etc through the console and write the input to a textfile. All of this works fine.
Now I want to input into the textfile when the project started and when it will end. That works without any problem.
Now here is my problem. I want to calculate the time the project lasts from the beginning to the end in days.
Currently it only calculates the days, ignoring the month and the year.
For example: (dd.mm.yyyy)
Start: 07.07.2014 End: 15.07.2014 Output: 8 (almost correct :) )
Another example:
Start 07.07.2014 End: 03.08.2014 Output: -3 (not even close)
I just cannot figure out where my problem is.
Thanks for your help! Chris
System.out.print("Start project (dd.mm.yyyy): ");
String beginn = input.nextLine();
DateFormat df = new SimpleDateFormat("dd.mm.yyyy");
Date d = null;
try {
d = df.parse(beginn);
} catch (ParseException e) {
System.out.println("Unable to parse " + beginn);
}
DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);
String s3 = df3.format(d);
System.out.print("End of project (dd.mm.yyyy): ");
String ende = input.nextLine();
DateFormat df4 = new SimpleDateFormat("dd.mm.yyyy");
Date g = null;
try {
d = df.parse(ende);
} catch (ParseException f) {
System.out.println("Unable to parse " + ende);
}
//DateFormat df5 = DateFormat.getDateInstance(DateFormat.LONG);
//String s4 = df5.format(d);
// String dauer = input.nextLine();
diffDays = 0;
try {
DateFormat dfa = new SimpleDateFormat("dd.mm.yyyy");
Date from = dfa.parse(beginn);
Date to = dfa.parse(ende);
long diffMillis = to.getTime() - from.getTime();
//diffDays = Math.round( (double)diffMillis / (24. * 60.*60.*1000.) );
diffDays = diffMillis / (1000 * 60 * 60 * 24);
System.out.println(diffDays);
} catch (ParseException ex) {
ex.printStackTrace();
}