我有周数和年份,我想得到一周的第一天和最后一天的日期,这是我的代码,它给了我错误的结果,请告诉我我是什么?做错了。提前谢谢。
SimpleDateFormat dt = new SimpleDateFormat("dd/mm/yyyy");
String start ="";
String end ="";
int week = 38;
int yeat = 2016;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year);
// firt day of week
start = dt.format(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 6);
//last day of week
end = dt.format(calendar.getTime());
答案 0 :(得分:1)
如果您使用Java 8+,则可以使用内置的周日期格式化程序:
int week = 38;
int year = 2016;
String weekYear = year + "-W" + week + "-7"; //2016-W38-7
LocalDate d = LocalDate.parse(year + "-W" + week + "-7", ISO_WEEK_DATE); //2016-09-25
注意:字符串末尾的-7
代表一周的最后一天(即星期日)。
答案 1 :(得分:1)
获取该特定周的周日和周六的日期 一年过去了。
SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy");
String start ="";
String end ="";
int week = 38;
int year = 2016;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
calendar.set(Calendar.WEEK_OF_YEAR, week);
start = dt.format(calendar.getTime());
calendar.set(Calendar.DAY_OF_WEEK,Calendar.SATURDAY);
end = dt.format(calendar.getTime());
System.out.println(start+" |"+end);
答案 2 :(得分:0)
试试这个:
SimpleDateFormat dt = new SimpleDateFormat("dd/mm/yyyy");
String start ="";
String end ="";
int week = 38;
int year = 2016;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year);
// firt day of week
Calendar cal = calendar;
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
cal.add(Calendar.DATE, -1);
}
start = dt.format(cal.getTime());
System.out.println(start);
Calendar cal1 = calendar;
while (cal1.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) {
cal1.add(Calendar.DATE, 1);
}
//last day of week
end = dt.format(cal1.getTime());
System.out.println(end);