package com.utcsoft.pcapps.selfservice.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 获取本周一的日期
System.out.println(df.format(cal.getTime()));
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);// 这种输出的是上个星期周日的日期,因为老外那边把周日当成第一天
cal.add(Calendar.WEEK_OF_YEAR, 1);// 增加一个星期,才是我们中国人理解的本周日的日期
System.out.println(df.format(cal.getTime()));
}
}
输出周一到周日的所有日期:
package com.utcsoft.pcapps.selfservice.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class Test {
/**
* 根据日期获得所在周的日期
* @param mdate
* @return
*/
@SuppressWarnings("deprecation")
public static List<Date> dateToWeek(Date mdate) {
int b = mdate.getDay();
Date fdate;
List<Date> list = new ArrayList<Date>();
Long fTime = mdate.getTime() - b * 24 * 3600000;
for (int a = 1; a <= 7; a++) {
fdate = new Date();
fdate.setTime(fTime + (a * 24 * 3600000));
list.add(a-1, fdate);
}
return list;
}
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd EEE");//EEE代表星期几
Date currentDate = new Date();
List<Date> days = dateToWeek(currentDate);
System.out.println("今天的日期: " + sdf.format(currentDate));
for (Date date : days) {
System.out.println(sdf.format(date));
}
}
}