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();
}
}