Java 获取最近一周的日期以及对应星期

1、偷懒直接贴代码,方便下次使用:

 /**
 * .Description://根据字符日期返回星期几
 * .Author:麦克劳林
 * .@Date: 2018/12/29
 */
public String getWeek(String dateTime){
    String week = "";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
        Date date = sdf.parse(dateTime);
        SimpleDateFormat dateFm = new SimpleDateFormat("EEEE");
        week = dateFm.format(date);
        week=week.replaceAll("星期","周");
    }catch (ParseException e){
        e.printStackTrace();
    }
    return week;
}

/**
 * 获取过去7天内的日期数组
 * @param intervals      intervals天内
 * @return              日期数组
 */
public ArrayList getDays(int intervals) {
    ArrayList pastDaysList = new ArrayList<>();
    for (int i = intervals -1; i >= 0; i--) {
        pastDaysList.add(getPastDate(i));
    }
    return pastDaysList;
}
/**
 * 获取过去第几天的日期
 * @param past
 * @return
 */
public String getPastDate(int past) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
    Date today = calendar.getTime();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String result = format.format(today);
    return result;
}

2、SQL根据日期查询某天数据

   
  select * from table_name where date_format(create_date,'%Y-%m-%d') = '2018-12-29';
   
  select *from table_name  where year(create_date) = '2018' and month(create_date) =  '12';

你可能感兴趣的:(Java 获取最近一周的日期以及对应星期)