我试着用下面的代码得到星期一的日期(今天是2016/5/6)
Calendar calendar1 = Calendar.getInstance();
calendar1.setFirstDayOfWeek(Calendar.MONDAY);
calendar1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar1.getTime();
但结果是
2016/4/25
,结果应该是2016/5/2
,5月份似乎是错的它在下面工作正常
Calendar calendar1 = Calendar.getInstance();
calendar1.setFirstDayOfWeek(Calendar.MONDAY);
calendar1.setTime(new Date());
calendar1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar1.getTime();
但当我在下面尝试的时候
public static Calendar createCalendar(Date date, int firstDayOfWeek) {
Calendar calendar = Calendar.getInstance();
if (date == null) return calendar;
calendar.setFirstDayOfWeek(firstDayOfWeek);
calendar.setTime(date);
return calendar;
}
public static Calendar[] getWeekStartEnd(Date date) {
Calendar[] calendars = new Calendar[2];
Calendar calendar = createCalendar(date, Calendar.MONDAY);
Calendar tempCalendar1 = createCalendar(date, Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
tempCalendar1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendars[0] = calendar;
calendars[1] = tempCalendar1;
return calendars;
}
它仍然不能正常工作
我想知道原因
最佳答案
您是否需要本周的第一天(假设当前日期==>2016/5/5
所以您可能需要第一天==>2016/5/2,这是星期一)
Calendar calendar = Calendar.getInstance();
// get device day
SimpleDateFormat formatter = new SimpleDateFormat("EEE");
String devicedaystring = formatter.format(calendar.getTime());
//get Device date
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
String devicedatestring = f.format(calendar.getTime());
String current_date = checkday(devicedatestring, devicedaystring);
// To Convert String date to Date object
SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = f1.parse( current_date);
private String checkDay(String date, String day)
{
if(day.equalsIgnoreCase("MON"))
{
return date;
}
else
{
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
String[] ss=date.split("-");
int yy = Integer.parseInt(ss[0]);
int MM = Integer.parseInt(ss[1]);
int dd = Integer.parseInt(ss[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(yy,MM-1,dd);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
date = f.format(calendar.getTime());
Logger.showVerboesLog("~~~", "First Day of Week === " +date);
return date;
}
}
关于android - 在Android中使用日历时,将一周的第一天设置为星期一后,获取星期一的日期不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37070178/