private static void getWeekByDate(Date time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式
Calendar cal = Calendar.getInstance();
cal.setTime(time);
// 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期
cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
String imptimeBegin = sdf.format(cal.getTime());
System.out.println("所在周星期一的日期:" + imptimeBegin);
cal.add(Calendar.DATE, 2);
String imptimeMi = sdf.format(cal.getTime());
System.out.println("所在周星期三的日期:" + imptimeMi);
cal.add(Calendar.DATE, 2);
String imptimeEnd = sdf.format(cal.getTime());
System.out.println("所在周星期五的日期:" + imptimeEnd);
}
获取当前是周几
public static final String getWeekZhCN(Date d1){
String weekDay = "";
String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
weekDay = weekDays[w];
return weekDay;
}
获取年月日
public String getDate() {
if (this.date== null) {
// Date d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(String.valu));//定义起始日期
Date d1 = recieveTime;
// SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("M");
SimpleDateFormat sdf2= new SimpleDateFormat("d");
String month = sdf1.format(d1);
String day = sdf2.format(d1);
this.date =month+"."+day;
}
return date;
将日期的年月日意外时间,安置为00
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();