计算两个日期之差,比如说租房软件,2017-02-08 租到2018-03-12 这其中是多少天呢。。
当然大家都会算,那么差多少个月 多少天么?
于是诞生了版本1
ong time = 205; //天long year = time / (365);long month = time % 365 /30;long day = time % 365 % 30; 这也简单。和计算时分秒的差不多,但是仔细想想按照需求还是差点。比如说2月到3月,对于房租按整月算还是差了点。房东可不干于是诞生了第二版。由于时间关系,代码也不整理了,测试没问题就发了。大家可以测测。虽然这不是好习惯。剩下的交给需求的你们来完成了
public static String getIntervalDate(Calendar c1,Calendar c2){ long milliseconds1 = c1.getTimeInMillis(); long milliseconds2 = c2.getTimeInMillis(); long diff = milliseconds2 - milliseconds1; long time = diff / (24 * 60 * 60 * 1000); System.out.PRintln("Time in days: " + time + " days."); int strMon = 0; int stryear = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR)); int month = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH); System.out.println("month" + month); int day = c2.get(Calendar.DATE) - c1.get(Calendar.DATE); if (day == 0) { if (month == 0) { if (stryear > 0) { System.out.println("最终==相差:" + stryear + "年" + month + "月" + day + "天"); } else { System.out.println("当天算你麻痹"); return "你麻痹 当天怎么算"; } } if (month > 0) { strMon=month; System.out.println("最终==相差:" + (stryear - 1) + "年" + (strMon) + "月" + day + "天"); } if (month < 0) { stryear--; System.out.println("最终==相差:" + (stryear - 1) + "年" + (strMon) + "月" + day + "天"); } return stryear + "~" + strMon + "~" + day; } else if (day > 0) { if (month == 0) { strMon = 0; } if (month > 0) { strMon = (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH)); } if (month < 0) { if (stryear > 0) { stryear--; strMon = 12-1; } else { strMon = 12 - 1; } } System.out.println("最终>>>>相差:" + stryear + "年" + (strMon) + "月" +day+ "天"); return stryear + "~" + (strMon) + "~" + day + "天"; } else if (day < 0) { if (month <= 0) { if (stryear > 0) { stryear--; strMon = 12; } } if (month > 0) { strMon = (c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH)); } System.out.println("最终<<<相差:" + stryear + "年" + (strMon - 1) + "月" + (c1.getMaximum(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH) + c2.get(Calendar.DAY_OF_MONTH))); return stryear + "~" + (strMon - 1) + "~" + (c1.getMaximum(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH) + c2.get(Calendar.DAY_OF_MONTH)); } return null; } public static void main(String[] args) { Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.set(2017, 02, 19); c2.set(2017, 02,20); System.out.println( getIntervalDate(c1,c2)); }有的小伙伴可能会问,写这么乱还发,哈哈哈我愿意。时间关系代码就到这了,有好想法留言给我~时间关系:下班了我要回家
新闻热点
疑难解答