JAVA取得1ヶ月の開始と終了時間および2つの日付が数ヶ月異なる
3209 ワード
一、一ヶ月の開始と終了時間コードは以下の通りである.
二、二ヶ月の日付が違う
三、テストコード
/**
*
* @param currentDate
* @return
*/
public static Date getStartDate(String currentDate){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(currentDate));
c.add(Calendar.MONTH, 0);
// 1 ,
c.set(Calendar.DAY_OF_MONTH, 1);
} catch (ParseException e) {
e.printStackTrace();
}
return c.getTime();
}
/**
*
* @param currentDate
* @return
*/
public static Date getEndDate(String currentDate){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(currentDate));
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
} catch (ParseException e) {
e.printStackTrace();
}
return c.getTime();
}
二、二ヶ月の日付が違う
/**
*
* @param start
* @param end
* @return
*/
public static int getMonth(Date start, Date end) {
if (start.after(end)) {
Date t = start;
start = end;
end = t;
}
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(start);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(end);
Calendar temp = Calendar.getInstance();
temp.setTime(end);
temp.add(Calendar.DATE, 1);
int year = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int month = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
if ((startCalendar.get(Calendar.DATE) == 1)&& (temp.get(Calendar.DATE) == 1)) {
return year * 12 + month + 1;
} else if ((startCalendar.get(Calendar.DATE) != 1) && (temp.get(Calendar.DATE) == 1)) {
return year * 12 + month;
} else if ((startCalendar.get(Calendar.DATE) == 1) && (temp.get(Calendar.DATE) != 1)) {
return year * 12 + month;
} else {
return (year * 12 + month - 1) < 0 ? 0 : (year * 12 + month);
}
}
三、テストコード
public static void main(String[] args) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String startDate = "2018-10-15 00:00:00";
String ednDate = "2019-11-10 23:59:59";
Date sdate = getStartDate(startDate);
Date edate = getEndDate(startDate);
System.out.println(" :" + sdf.format(sdate));
System.out.println(" :" + sdf.format(edate));
int month = getMonth(sdf.parse(startDate), sdf.parse(ednDate));
System.out.println(" :" + month);
}