我正在使用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”。 请帮帮我
由于
答案 0 :(得分: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);
答案 1 :(得分: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);
}
今天您可以使用精确格式
分配任何其他日期,而不是今天分配