为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_遁去的一_1 2018-07-14 10:18:33
这是从网上复制的 不知道对不对 最好能解释下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); }}
查看完整描述

1 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

因为是两个日期差,所以可能第一个大,也可能第二个大,所以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);


查看完整回答
反对 回复 2018-08-05
  • 1 回答
  • 0 关注
  • 1381 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号