猿问

Oracle 的months_between(函数)转成java代码

这是从网上复制的 不知道对不对 
最好能解释下months_between(函数)的源码是怎么操作的 
public class Months_between {

/**
 * 计算两个日期相差的月份数
 *
 * @param date1 日期1
 * @param date2 日期2
 * @param pattern  日期1和日期2的日期格式
 * @return 相差的月份数
 * @throws
 */
private Date date1;
private Date date2;

public static int countMonths(String date1, String date2, String pattern) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    Calendar c1 = Calendar.getInstance();
    Calendar c2 = Calendar.getInstance();

    c1.setTime(sdf.parse(date1));
    c2.setTime(sdf.parse(date2));

    int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);

    /*//开始日期若小月结束日期
    if (year < 0) {
        year = -year;
        return year * 12 + c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
    }*/

    return year * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
}

}


qq_遁去的一_1
浏览 1382回答 1
1回答

慕妹3242003

因为是两个日期差,所以可能第一个大,也可能第二个大,所以if (year < 0) 后需要颠倒下year * 12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);颠倒下就是-year * 12 - c2.get(Calendar.MONTH) + c1.get(Calendar.MONTH);也就是return -year * 12 + c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);也就是year = -year;return year * 12 + c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
随时随地看视频慕课网APP

相关分类

Java
我要回答