工具类--日期工具类


public class DateUtils {

/**
* 获取两个日期之间的所有日期
*/
public static List<Date> getBetweenDates(Date begin, Date end) {
List<Date> result = new ArrayList<Date>();
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(begin);
while(begin.getTime()<=end.getTime()){
result.add(tempStart.getTime());
tempStart.add(Calendar.DAY_OF_YEAR, 1);
begin = tempStart.getTime();
}
return result;
}

/**
* 获取当天 前几天的日期-1 2019-04-21 11:59:59
* @return fewDays
*/
public static String getBeforeDay(String fewDays){
int days = Integer.valueOf(fewDays).intValue();
days = days +1;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
//获取日历实例
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
//设置为前几天
calendar.add(Calendar.DAY_OF_MONTH, -days);
return sdf.format(calendar.getTime());
}

/**
* 获取当天 前一天的日期 2019-04-21 11:59:59
* @return fewDays
*/
public static String getBeforeOneDay(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
//获取日历实例
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
//设置为前几天
calendar.add(Calendar.DAY_OF_MONTH, -1);
return sdf.format(calendar.getTime());
}

/**
* 获取当前年度
* @author: donghaijian
* @return
*/
public static String getCurrentYear() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
Date date = new Date();
return sdf.format(date);
}

public static String parseDateToString(String pattern, Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}

private static Date parseStringToDate(String pattern, String dateTime) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
return sdf.parse(dateTime);
} catch (ParseException e) {
log.error(e.getMessage(), e);
return null;
}
}

public static boolean parseWeChatDate(String date) {
if(date.length() != 8){
return true;
}
try {
Integer.parseInt(date);
} catch (Exception e) {
log.error(e.getMessage(), e);
return true;
}
return false;
}

/**
* 将一个字符串用给定的格式转换为日期类型。<br>
* 注意:如果返回null,则表示解析失败
*
* @param datestr
* 需要解析的日期字符串
* @param pattern
* 日期字符串的格式,默认为“yyyy-MM-dd”的形式
* @return 解析后的日期
*/
public static Date parse(String datestr, String pattern) {
Date date = null;
if (null == pattern || "".equals(pattern)) {
pattern = YYYY_MM_DD;
}
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
date = dateFormat.parse(datestr);
} catch (ParseException e) {
}
return date;
}

/**
* 获取指定时间N天前或者N天后的 日期
* @param date 指定时间
* @param n 正数后 负数前
* @return date
*/
public static Date getNday(Date date, int n) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, n);
return calendar.getTime();
}


}
原文地址:https://www.cnblogs.com/tieandxiao/p/10931137.html