import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateTai { //判断两个日期的先后顺序 public static void test1(String startdate,String enddate){ //如果startdate在enddate的后面,则调换它们的值。 if(java.sql.Date.valueOf(startdate).after(java.sql.Date.valueOf(enddate))){ String tai = startdate; startdate = enddate; enddate = tai; } } //判断日期date是否在日期段startdate-enddate之间 public static boolean test2(String date,String startdate,String enddate){ if(date.equals(startdate)||date.equals(enddate)){ return true; } boolean tai = false; if(java.sql.Date.valueOf(date).after(java.sql.Date.valueOf(startdate))){ if(java.sql.Date.valueOf(enddate).after(java.sql.Date.valueOf(date))){ tai = true; } } return tai; } //判断某一天是星期几 public static String getWeekDay(String date) throws ParseException{ String dayNames[] = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date d = sdf.parse(date); Calendar calendar = Calendar.getInstance(); calendar.setTime(d); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); //System.out.println(dayNames[dayOfWeek - 1]); return dayNames[dayOfWeek - 1]; } //打印出两个日期之间的所有日期 //将所有日期插入一数组,返回。数组的首尾两个元素分别是dateStart和dateEnd public static String[] getDayAtTwoDate(String dateStart,String dateEnd){ test1(dateStart,dateEnd); //确保dateStart在dateEnd的后面 int length = getDays(dateStart, dateEnd); String[] tai = new String[length]; int i = 0; SimpleDateFormat sdfStart = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdfEnd = new SimpleDateFormat("yyyy-MM-dd"); try{ sdfStart.parse(dateStart); Calendar clStart = sdfStart.getCalendar(); sdfEnd.parse(dateEnd); Calendar clEnd = sdfEnd.getCalendar(); while(true){ if(clStart.before(clEnd)||clStart.equals(clEnd)){ System.out.println(sdfStart.format(clStart.getTime())); tai[i] = sdfStart.format(clStart.getTime()); i++; clStart.add(clStart.DAY_OF_MONTH ,1 ); clStart.set(clStart.DAY_OF_MONTH,clStart.get(clStart.DAY_OF_MONTH)); }else{ break ; } } }catch(ParseException ex ){ ex.printStackTrace(); } return tai; } //得到两段日期之间的天数(必须确保dateStart在dateEnd的后面) //例如传入参数为:2009-04-12 和 2009-04-14,则返回 3. public static int getDays(String dateStart,String dateEnd){ int days = 0; SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd"); try { Date date1 = ft.parse( dateStart ); Date date2 = ft.parse( dateEnd ); days = (int) (date2.getTime() - date1.getTime()); days = Math.abs(days / 1000 / 60 / 60 / 24)+1; } catch (ParseException e) { e.printStackTrace(); } return days; } //测试 public static void main(String[] args) { String[] tai = DateTai.getDayAtTwoDate("2009-04-23", "2009-05-10"); for (int i = 0; i < tai.length; i++) { System.out.println(tai[i]); } /*String date = "2009-04-16"; String startdate = "2009-04-15"; String enddate = "2009-04-15"; System.out.println(DateTai.test2(date, startdate, enddate));*/ } }
posted on 2009-04-19 18:12 台哥编程课堂 阅读(148) 评论(0) 编辑 收藏 举报