Soldato
- Joined
- 24 Apr 2011
- Posts
- 5,455
Guys, I need your help. I am trying to work out how to calculate the number of NIGHTS between 2 dates. Therefore, the number of nights between 1st Jan and 31st Jan is 30, and the number between 1st Jan and 1st Feb is 31.
Here is what I have till now:
Shamelessly, i took a template off the internet and modded it to my use. Anyway, it works fine when I use dates in the same month, but goes haywire when i chose different months.
To use the same examples as before, it gives me 30 days between 1st Jan and 31st Jan, but 29 days between 1st Jan and 1st Feb.
Any ideas?
Its probably blatantly obvious, but I can't see it.
Here is what I have till now:
import java.util.*;
public class DateDifference {
int day1, day2, month1, month2, year1, year2, days;
public static void main(String args[]){
DateDifference difference = new DateDifference();
}
DateDifference() {
Calendar cal1 = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
Scanner sc = new Scanner (System.in);
System.out.println("Enter Day:");
day1 = sc.nextInt();
System.out.println("Enter Month:");
month1 = sc.nextInt();
System.out.println("Enter Year:");
year1 = sc.nextInt();
System.out.println("Enter Day:");
day2 = sc.nextInt();
System.out.println("Enter Month:");
month2 = sc.nextInt();
System.out.println("Enter Year:");
year2 = sc.nextInt();
cal1.set(year1, month1, day1);
cal2.set(year2, month2,day2);
System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
}
public int daysBetween(Date cal1, Date cal2){
return (int)( (cal2.getTime() - cal1.getTime()) / (1000 * 60 * 60 * 24));
}
}
Shamelessly, i took a template off the internet and modded it to my use. Anyway, it works fine when I use dates in the same month, but goes haywire when i chose different months.
To use the same examples as before, it gives me 30 days between 1st Jan and 31st Jan, but 29 days between 1st Jan and 1st Feb.
Any ideas?
Its probably blatantly obvious, but I can't see it.