根据开始时间和结束时间相差天数,生成期间每一天的日期

阅读更多


/**
* 根据开始时间和结束时间相差天数,生成期间每一天的日期
* @param startDate 开始时间
* @param days 前后时间相差天数
* @return
*/
public static List createYMD(Date startDate,Long days){
List ls=new ArrayList();
String ymd=null;
for(int i=0;i<=days;i++){
ymd=TimeRule.dateTodateStr(TimeRule.plusDate(startDate, i));
ls.add(ymd);
}
return ls;
}

/**
* 将日期转换成 日期(yyyy-MM-dd)字符串.
* @param date 日期
* @return
*/  
public static String dateTodateStr(final Date date) {
return dateToStr(date, "yyyy-MM-dd");
}

/**
* 将日期转换成指定格式的字符串.
* @param date 日期
* @param dateFormat 日期格式. 如果为空,默认为:yyyy-MM-dd HH:mm:ss.
* @return
*/  
public static String dateToStr(final Date date, String dateFormat) {
if (date == null){
//log.debug("未知时间");
return "";
//return "未知时间";
}
try{
if(dateFormat == null || dateFormat.trim().length() ==0)
dateFormat = "yyyy-MM-dd HH:mm:ss";
DateFormat fmt = new SimpleDateFormat(dateFormat.trim());
return fmt.format(date);
}catch(Exception ex){
log.error("将日期转换成指定格式("+ dateFormat +")的字符串时失败!错误原因:"+ex.getMessage());
return "";
     //return "日期格式不匹配";
}
}


/**
* 返回加上指定天数的日期.
* @param date 将运算日期.
* @param day 加上的天数.
* return
*/
public static Date plusDate(final Date date, final int day){
try{
java.util.Calendar calendar=java.util.Calendar.getInstance();  
        calendar.setTime(date);
        int currDay = java.util.Calendar.DAY_OF_MONTH;
       
        calendar.set(currDay, calendar.get(currDay) + day); //让日期加 day天

        return calendar.getTime();
}catch(Exception ex){
return null;
}
}

你可能感兴趣的:(生成两个日期之间的每一天)