Obtain the elapsed date (such as 0 years, 0 months, 0 days) from the two dates. Example 2020/08/01 and 2020/08/03 → 0 years 0 months 2 days 2020/08/01 and 2020/09/01 → 0 years, 1 month, 0 days 2020/08/01 and 2021/08/01 → 1 year 0 months 0 days
-From date> To date returns an error (error code: -1) ・ Date format is yyyy / MM / dd only -From date and To date are both String type ・ Return year, month, and day with int [](0: year, 1: month, 2: day)
public static int getDateDiff(String paraFromDate, String paraToDate, int[] paraDiffDay) {
int diffYear = 0 ;
int diffMonth = 0 ;
int diffDay = 0 ;
//Break down the date of the start date into year, month, and day(From)
int from_year = parseInt(paraFromDate.substring(0,4)) ;
int from_month = parseInt(paraFromDate.substring(5,7)) ;
int from_day = parseInt(paraFromDate.substring(8,10)) ;
//Break down the base date into year, month, and day(To)
int to_year = parseInt(paraToDate.substring(0,4)) ;
int to_month = parseInt(paraToDate.substring(5,7)) ;
int to_day = parseInt(paraToDate.substring(8,10)) ;
Calendar comp_from = Calendar.getInstance() ;
comp_from.set(from_year, from_month - 1, from_day) ;
Calendar comp_to = Calendar.getInstance() ;
comp_to.set(to_year, to_month - 1, to_day) ;
//Starting date>If it is a base date, make an error
if(comp_from.compareTo(comp_to) > 0) {
return -1;
}
//Get the year difference
diffYear = to_year - from_year ;
//Compare months
if(from_month > to_month) {
//When the month of the starting date is larger=Across the year
to_month = to_month + 12 ;
//Minus year
//If it is the same year from_The month can never be bigger, so it can't be negative
diffYear = diffYear - 1 ;
}
//Get the difference between the months
diffMonth = to_month - from_month ;
//Compare days
//Starting date(From)If is larger, it is judged that it straddles the moon
if(from_day > to_day) {
//Add the maximum number of start dates
to_day = to_day + comp_from.getActualMaximum(comp_from.DATE) ;
//Minus the difference between the months
diffMonth = diffMonth - 1 ;
}
//Get the difference between days
diffDay = to_day - from_day ;
//Set in argument
paraDiffDay[0] = diffYear ;
paraDiffDay[1] = diffMonth ;
paraDiffDay[2] = diffDay ;
return 0 ;
}
Caller
String fromDate = '2020/08/20' ;
String toDate = '2020/10/01' ;
int diffDate[] = {0,0,0} ;
if( getDateDiff(fromDate, toDate, diffDate) != 0 ) {
//error
}
else {
String keikaDate = diffDate[0] + "Year" + diffDate[1] + "Months" + diffDate[2] + "Day" ;
}
・ No error handling → Exception occurs if the argument date is not in the format of yyyy / MM / dd → If the date does not exist even if it is in yyyy / MM / dd format, the behavior is incorrect.
-Get the maximum number of days in the month using getActualMaximum → At first 31st in January, 3,5,7,8,10, December 30th in April, June, September and November February was 29 days in leap years, 28 days otherwise. Solved with a sentence of getActualMaximum.
Recommended Posts