我知道一年中的周数,一周从星期日开始,然后是星期一,星期二......星期六。
由于我知道周数,使用Java代码获取特定周的日期的有效方法是什么?
答案 0 :(得分:36)
如果您不想使用外部库,只需使用日历。
SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 23);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(sdf.format(cal.getTime()));
答案 1 :(得分:19)
基于this:
final long calendarWeek = 34;
LocalDate desiredDate = LocalDate.now()
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, calendarWeek)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
答案 2 :(得分:11)
您可以使用joda time库
int weekNumber = 10;
DateTime weekStartDate = new DateTime().withWeekOfWeekyear(weekNumber);
DateTime weekEndDate = new DateTime().withWeekOfWeekyear(weekNumber + 1);
答案 3 :(得分:3)
您没有提到您确切需要的返回类型,但此代码应该对您有用。 sysouts和formatter只是为了显示结果。
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.WEEK_OF_YEAR, 30);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(formatter.format(cal.getTime()));
cal.add(Calendar.DAY_OF_WEEK, 6);
System.out.println(formatter.format(cal.getTime()));
答案 4 :(得分:0)
此答案与其他答案几乎相同。但是,事情就这样了:
int year = 2018;
int week = 27;
int day = 1; //assuming week starts from sunday
Calendar calendar = Calendar.getInstance();
calendar.setWeekDate(year, week, day);
System.out.println(calendar.getTime());
答案 5 :(得分:0)
for(int i=1; i<=7; i++) {
if(i <= 3) {
LocalDate desiredDate = LocalDate.now()
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 26)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.of(i)));
System.out.println(desiredDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
} else {
LocalDate desiredDate = LocalDate.now()
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 26)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.of(i)));
System.out.println(desiredDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
}
}
此代码段根据给定的周数提供从星期一到星期日的日期 输出: