0

我正在使用 DatePickerDialog 来显示日历。我想访问所选日期的一周的第一天和最后一天。

这是我尝试过的

     this.tv_date.setText( new StringBuilder()
        // Month is 0 based so add 1
                    .append(mDay).append("-")
                    .append(monthName).append("-")
                    .append(mYear).append(""));
        tv_date.setHighlightColor(Color.CYAN);

        String str=mDay+"-"+mMonth+"-"+mYear;

        SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
        sdf.format(""+str); //here I am getting exception

        Calendar cal=Calendar.getInstance();

        int s=  cal.getFirstDayOfWeek();

        Toast.makeText(getApplicationContext(), "first day of the week : "+s, 1).show();

但我收到“IllegalArguementException”。请帮我

谢谢

4

2 回答 2

4

sdf.format(""+str);- 是错的。您要么需要将Date对象传递给它,要么将其更改为sdf.parse(str);以从中获取Date对象。

编辑:-要获得一周的第一天,请执行此操作。

String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
Date myDate = new Date();
try{
    myDate = sdf.parse(str);
}catch(ParseException pe){
    // Do Something
}
Calendar cal = Calendar.getInstance();  
cal.setTime(myDate);
cal.set(Calendar.DAY_OF_WEEK, 1);  
int s = cal.get(Calendar.DATE);
于 2013-03-01T06:44:14.937 回答
0

这是计算一周中第一天的示例。

private void firstDayOfThisWeek(){
 DateTime today = DateTime.today(TimeZone.getDefault()); 
 DateTime firstDayThisWeek = today; //start value 
 int todaysWeekday = today.getWeekDay();
 int SUNDAY = 1;
 if(todaysWeekday > SUNDAY){
   int numDaysFromSunday = todaysWeekday - SUNDAY;
   firstDayThisWeek = today.minusDays(numDaysFromSunday);
 }
 System.out.println("The first day of this week is : " + firstDayThisWeek);
}

除了今天分配,您还可以使用精确格式分配任何其他日期

于 2013-03-01T06:41:04.233 回答