日期:2014-05-20 浏览次数:20774 次
public int betweenDays(Calendar beginDate, Calendar endDate) { if (beginDate.get(Calendar.YEAR) == endDate.get(Calendar.YEAR)) { return endDate.get(Calendar.DAY_OF_YEAR) - beginDate.get(Calendar.DAY_OF_YEAR); } else { if (beginDate.getTimeInMillis() < endDate.getTimeInMillis()) { int days = beginDate.getActualMaximum(Calendar.DAY_OF_YEAR) - beginDate.get(Calendar.DAY_OF_YEAR) + endDate.get(Calendar.DAY_OF_YEAR); for (int i = beginDate.get(Calendar.YEAR) + 1; i < endDate .get(Calendar.YEAR); i++) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, i); days += c.getActualMaximum(Calendar.DAY_OF_YEAR); } return days; } else { int days = endDate.getActualMaximum(Calendar.DAY_OF_YEAR) - endDate.get(Calendar.DAY_OF_YEAR) + beginDate.get(Calendar.DAY_OF_YEAR); for (int i = endDate.get(Calendar.YEAR) + 1; i < beginDate .get(Calendar.YEAR); i++) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, i); days += c.getActualMaximum(Calendar.DAY_OF_YEAR); } return days; } } }
------解决方案--------------------
有年月日的好办。
只有月日的,不知怎么考虑2/29 ,或者 是否支持 12-1 到 1-1
------解决方案--------------------
package com.cme.LanDian; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; /* * 输入某年某月某日,判断这一天是这一年的第几天? */ public class GetDateDays { public static void main(String[] args) { System.out.println("请输入一个日期:"); String dateString = nnew Scanner(System.in).nextLine(); String yearBegin = dateString.substring(0, 4) + "-01-01"; // 定义日期格式: SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd"); try { Date date = sdf.parse(dateString);// 通过日期格式的parse()方法将字符串转换成日期 Date dateBegin = sdf.parse(yearBegin); long l = date.getTime() - dateBegin.getTime(); l = l / 1000 / 60 / 60 / 24; System.out.println(l); } catch (ParseException e) { e.printStackTrace(); } } }
------解决方案--------------------
date4j
------解决方案--------------------
把日期转化成毫秒,相减得到毫秒数,然后再转化为天
------解决方案--------------------