Given two dates in AD, find number of days between these 2 dates
https://github.com/mission-peace/interview/blob/master/src/com/interview/misc/DayDifferenceBetweenTwoDates.java
private static final int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
public int diff(int year1,int month1, int day1,int year2, int month2,int day2){
int days1 = year1*365 + day1;
int days2 = year2*365 + day2;
for(int i=0; i < month1-1; i++){
days1 = days1 + days[i];
}
for(int i=0; i < month2-1; i++){
days2 = days2 + days[i];
}
days1 = days1 + (year1-1)/4 - (year1 -1)/100 + (year1 -1 )/400;
days2 = days2 + (year2-1)/4 - (year2 -1)/100 + (year2 -1 )/400;
if(isLeapYear(year1) && month1 > 2){
days1++;
}
if(isLeapYear(year2) && month2 > 2){
days2++;
}
return days2 - days1;
}
public boolean isLeapYear(int year){
if(year % 400 == 0){
return true;
}
if(year % 4 == 0 && year % 100 != 0){
return true;
}
return false;
}
https://github.com/mission-peace/interview/blob/master/src/com/interview/misc/DifferenceBetweenTwoTime.java
* Given two times in four digits number e.g 10:10 is 1010 find difference between them
* Test cases
* Time 1 better be less than equal to time 2
* First 2 digits better be between 0 and 23
* Last 2 digits of number better be between 0 to 59
public int diff(int time1, int time2){
if(time2 < time1){
throw new IllegalArgumentException();
}
int hourDiff = time2/100 - time1/100 -1;
int minDiff = time2%100 + (60 - time1%100);
if(minDiff >= 60){
hourDiff++;
minDiff = minDiff - 60;
}
return hourDiff*100 + minDiff;
}
https://github.com/mission-peace/interview/blob/master/src/com/interview/misc/DayDifferenceBetweenTwoDates.java
private static final int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
public int diff(int year1,int month1, int day1,int year2, int month2,int day2){
int days1 = year1*365 + day1;
int days2 = year2*365 + day2;
for(int i=0; i < month1-1; i++){
days1 = days1 + days[i];
}
for(int i=0; i < month2-1; i++){
days2 = days2 + days[i];
}
days1 = days1 + (year1-1)/4 - (year1 -1)/100 + (year1 -1 )/400;
days2 = days2 + (year2-1)/4 - (year2 -1)/100 + (year2 -1 )/400;
if(isLeapYear(year1) && month1 > 2){
days1++;
}
if(isLeapYear(year2) && month2 > 2){
days2++;
}
return days2 - days1;
}
public boolean isLeapYear(int year){
if(year % 400 == 0){
return true;
}
if(year % 4 == 0 && year % 100 != 0){
return true;
}
return false;
}
https://github.com/mission-peace/interview/blob/master/src/com/interview/misc/DifferenceBetweenTwoTime.java
* Given two times in four digits number e.g 10:10 is 1010 find difference between them
* Test cases
* Time 1 better be less than equal to time 2
* First 2 digits better be between 0 and 23
* Last 2 digits of number better be between 0 to 59
public int diff(int time1, int time2){
if(time2 < time1){
throw new IllegalArgumentException();
}
int hourDiff = time2/100 - time1/100 -1;
int minDiff = time2%100 + (60 - time1%100);
if(minDiff >= 60){
hourDiff++;
minDiff = minDiff - 60;
}
return hourDiff*100 + minDiff;
}