我想在 java 中使用 Calendar 和 Date 获取一周的第一个日期,输入为 :: 1. 月的周数 2. 月 3. 年
Calendar cal = Calendar.getInstance();
int weekOfMonth = Calendar.WEEK_OF_MONTH;
System.out.println("weekOfMonth : " + weekOfMonth);
在此之后我不知道继续。
在 Calendar 类中有一个方法 getFirstDayOfWeek() ,它将以 0 表示周日,1 表示周一,依此类推。以下代码片段基于此,将为您提供一周中的第一个日期。
private static Date getFirstDateOfWeek(){
Calendar cal = Calendar.getInstance();
Date d = Calendar.getInstance().getTime();
int currDay = d.getDay(); // getting the current day
int startDay = (currDay - cal.getFirstDayOfWeek()) + 1; // calculate the difference of number days to the current date from the first day of week
d.setDate(d.getDate() - startDay); // setting the date accordingly.
return d;
}
希望这会帮助你。
int year = 2012;
int month = 3 //for April(they start from 0 = January)
int week = 2;
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEEK_OF_MONTH, week);
Date date = calendar.getTime();