Java中有关日期的操作,昨天晚上赴约,搞到12点多才回来,今天写这一小段代码都花了一段漫长的时间,哎。。
代码奉上:
/** * * @param date * @return which month is belonged to the param date * @author Xing,Xiudong */ public int getMonthOfDate(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); Date firstDayOfNextMonth = DateTools.getFirstSatudayOfMonth( month == 11 ? ++year : year, month == 11 ? 0 : ++month); Date lastDayOfMonth = DateUtils.addDays(firstDayOfNextMonth, -1); c.setTime(date); int result = c.get(Calendar.MONTH); return date.after(lastDayOfMonth) ? ++result : result; } /** * * @param date * @return which year is belonged to the param date * @author Xing,Xiudong */ public int getYearOfDate(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); int year = c.get(Calendar.YEAR); c.set(++year, 1, 1); Date firstDayOfYear = DateTools.getFirstSatudayOfMonth(c .get(Calendar.YEAR), 0); int result = c.get(Calendar.YEAR); return date.before(firstDayOfYear) ? --result : result; }
加上以前的代码:
/** * * @param date * @return first day(Satuday) of month * @author Jin, QingHua */ public static Date getFirstSatudayOfMonth(int year, int month) { Calendar cal = GregorianCalendar.getInstance(); cal.set(year, month, 1); cal.setFirstDayOfWeek(Calendar.SATURDAY); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); return cal.getTime(); } /** * * @param date * @return first day(Satuday) of week * @author Wu,Yang */ public static Date getFirstSatudayOfWeek(Date date) { Calendar cal = GregorianCalendar.getInstance(); cal.setTime(date); cal.setFirstDayOfWeek(Calendar.SATURDAY); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); return cal.getTime(); } /** * * @param date * @return week count of month of date * @author Xing,Xiudong */ public Integer getWeekCountOfMonth(int year, int month) { Date first_day_month = DateTools .getFirstSatudayOfMonth(year, month - 1); Calendar cal_lastly = Calendar.getInstance(); cal_lastly.set(year, month, 1); Date firstDayofNextMonth = cal_lastly.getTime(); Integer count = 0; for (Date first_day_week = first_day_month; first_day_week .before(firstDayofNextMonth); first_day_week = DateUtils .addDays(first_day_week, 7)) { count++; } return count; }
Java中有关日期的操作 昨天晚上赴约 搞到12点多才回来 今天写这一小段代码都花了一段漫长的时间 哎。。...