0

实际上,在我的 java 程序中,User give Start Dateand end Dateex:2012-12-01 和 2012-12-30 现在我们可以在开始日期和结束日期之间返回结果。

如果我们每天都想要,我们可以使用以下代码...

List<Date> dates = new ArrayList<Date>();
     DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
    String str_date ="2012-12-03";
    String end_date ="2012-12-06";
    Date startDate = (Date) formatter.parse(str_date);
    Date endDate = (Date) formatter.parse(end_date);

    Calendar cal = Calendar.getInstance();
    Calendar cal1 = Calendar.getInstance();
    cal.setTime(startDate);
    cal1.setTime(endDate);
    int i=0; // use this for alternative date print
    while (!cal.equals(cal1)) {

        cal.add(Calendar.DATE, 1);
             System.out.println(cal.getTime()); 

        }

但问题并非如此,问题是用户只想要Monday,sunday他的开始日期和结束日期中的日期,然后如何检查那个....

For Ex: String userWeeks="SUNDAY,MONDAY";

这是用户字符串,然后是如何将Calendar日期与此userWeeks字符串进行比较。

首先我们可以拆分字符串userWeeks.split(",")然后我们分开SUNDAY MONDAY

So How to compare This String into Calendar?
4

3 回答 3

1

在你的循环中添加 if 条件

 while (!cal.equals(cal1)) {
          cal.add(Calendar.DATE, 1);
          int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
          if((Calendar.MONDAY==dayOfWeek)||(Calendar.SUNDAY==dayOfWeek)){
            System.out.println(cal.getTime());
          }
        }
于 2012-12-07T05:25:28.960 回答
1

像这样检查

int day=cal.get(Calendar.DAY_OF_WEEK);
if(day == Calendar.SUNDAY)
{
//it is sunday
}

用于检查字符串

HashMap<String,Integer> daysOfWeeks=new HashMap<String,Integer>();
daysOfWeek.put("SUNDAY",new Integer(Calendar.SUNDAY));
//and the rest

然后

String day=//user input;
Integer i=daysOfWeek.get(day)
if(i!=null)
{
if(i==Calendar.SUNDAY)
{
//it is sunday;
}
}
于 2012-12-07T05:28:25.167 回答
0

最后我在想这样我的代码有什么问题请讨论我..

    import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class SimpleDateFormatClass 
{
    public static void main(String args[]) throws Exception
    {
         DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
            String str_date ="2012-12-01";
            String end_date ="2012-12-10";
            Date startDate = (Date) formatter.parse(str_date);
            Date endDate = (Date) formatter.parse(end_date);
            Calendar cal = Calendar.getInstance();
            Calendar cal1 = Calendar.getInstance();
            cal.setTime(startDate);
            cal1.setTime(endDate);
    while (!cal.equals(cal1))
    {       
                cal.add(Calendar.DATE, 1);      

         String days="Fri,mon,tue";
          for (String retval: days.split(","))
            {
        SimpleDateFormat sdf= new SimpleDateFormat("EEEE");
        Date date1= sdf.parse(retval);

              if(date1.getDay()==cal.get(Calendar.DAY_OF_WEEK))
                  {
                       System.out.println(cal.getTime());
                  }
           // System.out.println(date1);
           }
    }//While
    }//Main
}
于 2012-12-07T11:05:51.293 回答