日期:2014-05-20 浏览次数:20776 次
//第一个 import java.text.SimpleDateFormat; import java.util.Calendar; public class MyObject { public static void main(String[] args) { // 2008-03-29 至 2008-05-21 SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd"); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.set(2008,2,29); c2.set( 2008,4,21); int days = c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR); for (int i = 0; i <= days; i++) { System.out.println(sm.format(c1.getTime())); c1.add( Calendar.DATE,1); } } }
------解决方案--------------------
public void printDate(Date begin, Date end) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); while (begin.before(end)) { System.out.println(sdf.format(begin)); } System.out.println(sdf.format(end)); } public void printDateWithoutWeekends(Date begin, Date end) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = GregorianCalendar.getInstance(); while (begin.before(end)) { cal.setTime(begin); if (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) System.out.println(sdf.format(begin)); } cal.setTime(end); if (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) System.out.println(sdf.format(end)); }
------解决方案--------------------
public class DateTest { private static Calendar from = Calendar.getInstance(); private static Calendar to = Calendar.getInstance(); public DateTest() { } /** * 初始化两个起始日期 * */ private void init() { from.set(2008, 2, 29); to.set(2008, 4, 21); } /** * 要求输出2008-03-29 至 2008-05-21 里面所有的日期。 * */ public void all() { init(); // 如果起始日期一直在结束日期之前,循环继续 while (from.before(to)) { printlnCalendar(from); // 日期增一 from.add(Calendar.DATE, 1); } } /** * 要求输出2008-03-29 至 2008-05-21 里面所有的日期(除去星期六,星期天) * */ public void withoutWeekend() { init(); // 用来标志是星期几的 int dayOfWeek = 0; while (from.before(to)) { // 得到from日期的星期 dayOfWeek = from.get(Calendar.DAY_OF_WEEK); if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY) { printlnCalendar(from); } // 日期增一 from.add(Calendar.DATE, 1); } } private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); /** * 打印日期,格式"年-月-日" */ private void printlnCalendar(Calendar c) { System.out.println(format.format(c.getTime())); } public static void main(String[] args) { DateTest dt = new DateTest(); dt.all(); dt.withoutWeekend(); } }
------解决方案--------------------
楼主说有些错误 是说不能包括 “2008-05-21” 吧?
void getDate(String d1,String d2) throws ParseException{ SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd"); Calendar c1=Calendar.getInstance(); Calendar c2=Calendar.getInstance(); c1.setTime(sd.parse(d1)); c2.setTime(sd.parse(d2)); c2.add(Calendar.DAY_OF_YEAR,-1); while(c1.before(c2)){ c1.add(Calendar.DAY_OF_YEAR, 1); int day=c1.get(Calendar.DAY_OF_WEEK); //if(day!=Calendar.SUNDAY&&day!=Calendar.SATURDAY) (除去星期六,星期天) System.out.println(sd.format(c1.getTime())); } }