我想使用日历和日期在java中获取一周的第一个日期,输入为:: 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;
}
希望这对您有帮助。
关于java - 获取一周的第一个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10119782/