java 返回某一天的周日和现在这一周的周日
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Test {
public static void main(String[] args) {
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()));
String str="2013-11-13 00:10:00";
SimpleDateFormat ddd=new SimpleDateFormat("dd");
System.out.println( getLastDayOfWeek(str) );
}
//返回某一天的周日
public static String getLastDayOfWeek(String string) {
String str=string;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = null;
try {
date=sdf.parse(str.toString());
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String s = format.format(c.getTime());
return s;
}
}
结果:
2013-11-11
2013-11-17
2013-11-17 12:10:00
另外,获取周一开始时间,获取周日开始时间
//返回某一天的周日
public static String getLastDayOfWeek(String string) {
String str=string;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date=sdf.parse(str.toString());
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String s = format.format(c.getTime());
s = s + " 23:59:59";
return s;
}
//返回某一天的周一
public static String getFirstDayOfWeek(String string) {
String str=string;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date=sdf.parse(str.toString());
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String s = format.format(c.getTime());
s = s + " 00:00:00";
return s;
}