目录
第一类:
第二类:
第一类:
package com.chinamcloud.spiderMember.util;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* 日期工具类
*/
@SuppressWarnings("ALL")
public class DateUtil {
/**
* 全局默认日期格式
*/
public static final String Format_Date = "yyyy-MM-dd";
/**
* 全局默认日期格式
*/
public static final String Format_Date_Dir = "yyyy/MM/dd";
/**
* 全局默认时间格式
*/
public static final String Format_Time = "HH:mm:ss";
/**
* 全局默认日期时间格式
*/
public static final String Format_DateTime = "yyyy-MM-dd HH:mm:ss";
/**
* 全局默认日期时间格式
*/
public static final String Format_DateTime1 = "yyyyMMddhhmmss";
/**
* 得到以yyyy-MM-dd格式表示的当前日期字符串
*/
public static String getCurrentDate() {
return new SimpleDateFormat(Format_Date).format(new Date());
}
/**
* 得到以yyyy/MM/dd格式表示的当前日期字符串dir
*/
public static String getCurrentDateDir() {
return new SimpleDateFormat(Format_Date_Dir).format(new Date());
}
/**
* 得到以yyyy/MM/dd格式表示的当前日期字符串dir
*/
public static String getCurrentDateDir(Date date) {
return new SimpleDateFormat(Format_Date_Dir).format(date);
}
/**
* 得到以format格式表示的当前日期字符串
*/
public static String getCurrentDate(String format) {
SimpleDateFormat t = new SimpleDateFormat(format);
return t.format(new Date());
}
/**
* 得到以HH:mm:ss表示的当前时间字符串
*/
public static String getCurrentTime() {
return new SimpleDateFormat(Format_Time).format(new Date());
}
/**
* 得到以format格式表示的当前时间字符串
*/
public static String getCurrentTime(String format) {
SimpleDateFormat t = new SimpleDateFormat(format);
return t.format(new Date());
}
/**
* 得到以yyyy-MM-dd HH:mm:ss表示的当前时间字符串
*/
public static String getCurrentDateTime() {
String format = DateUtil.Format_Date + " " + DateUtil.Format_Time;
return getCurrentDateTime(format);
}
/**
* 今天是星期几
*
* @return
*/
public static int getDayOfWeek() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 指定日期是星期几
*
* @param date
* @return
*/
public static int getDayOfWeek(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 今天是本月的第几天
*
* @return
*/
public static int getDayOfMonth() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 指定日期是当月的第几天
*
* @param date
* @return
*/
public static int getDayOfMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取某一个月的天数
*
* @param date
* @return
*/
public static int getMaxDayOfMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.getActualMaximum(Calendar.DATE);
}
/**
* 以yyyy-MM-dd格式获取某月的第一天
*
* @param date
* @return
*/
public static String getFirstDayOfMonth(String date) {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date));
cal.set(Calendar.DAY_OF_MONTH, 1);
return new SimpleDateFormat(Format_Date).format(cal.getTime());
}
/**
* 今天是本年的第几天
*
* @return
*/
public static int getDayOfYear() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.DAY_OF_YEAR);
}
/**
* 指定日期是当年的第几天
*
* @param date
* @return
*/
public static int getDayOfYear(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_YEAR);
}
/**
* 以yyyy-MM-dd解析字符串date,并返回其表示的日期是周几
*
* @param date
* @return
*/
public static int getDayOfWeek(String date) {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date));
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 以yyyy-MM-dd解析字符串date,并返回其表示的日期是当月第几天
*
* @param date
* @return
*/
public static int getDayOfMonth(String date) {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date));
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 以yyyy-MM-dd解析字符串date,并返回其表示的日期是当年第几天
*
* @param date
* @return
*/
public static int getDayOfYear(String date) {
Calendar cal = Calendar.getInstance();
cal.setTime(parse(date));
return cal.get(Calendar.DAY_OF_YEAR);
}
/**
* 以指定的格式返回当前日期时间的字符串
*
* @param format
* @return
*/
public static String getCurrentDateTime(String format) {
SimpleDateFormat t = new SimpleDateFormat(format);
return t.format(new Date());
}
/**
* 以yyyy-MM-dd格式输出只带日期的字符串
*/
public static String toString(Date date) {
if (date == null) {
return "";
}
return new SimpleDateFormat(Format_Date).format(date);
}
/**
* 以yyyy-MM-dd HH:mm:ss输出带有日期和时间的字符串
*/
public static String toDateTimeString(Date date) {
if (date == null) {
return "";
}
return new SimpleDateFormat(Format_DateTime).format(date);
}
/**
* 以yyyy-MM-dd HH:mm:ss输出带有日期和时间的字符串
*/
public static String toDateTimeString(DateTime date) {
if (date == null) {
return "";
}
return org.joda.time.format.DateTimeFormat.forPattern(Format_DateTime).print(date);
}
/**
* 按指定的format输出日期字符串
*/
public static String toString(Date date, String format) {
SimpleDateFormat t = new SimpleDateFormat(format);
return t.format(date);
}
/**
* 以HH:mm:ss输出只带时间的字符串
*/
public static String toTimeString(Date date) {
if (date == null) {
return "";
}
return new SimpleDateFormat(Format_Time).format(date);
}
/**
* 以yyyy-MM-dd解析两个字符串,并比较得到的两个日期的大小
*
* @param date1
* @param date2
* @return
*/
public static int compare(String date1, String date2) {
return compare(date1, date2, Format_Date);
}
/**
* 以HH:mm:ss解析两个字符串,并比较得到的两个时间的大小
*
* @param time1
* @param time2
* @return
*/
public static int compareTime(String time1, String time2) {
return compareTime(time1, time2, Format_Time);
}
/**
* 以指定格式解析两个字符串,并比较得到的两个日期的大小
*
* @param date1
* @param date2
* @param format
* @return
*/
public static int compare(String date1, String date2, String format) {
Date d1 = parse(date1, format);
Date d2 = parse(date2, format);
return d1.compareTo(d2);
}
/**
* 以指定解析两个字符串,并比较得到的两个时间的大小
*
* @param time1
* @param time2
* @param format
* @return
*/
public static int compareTime(String time1, String time2, String format) {
String[] arr1 = time1.split(":");
String[] arr2 = time2.split(":");
if (arr1.length < 2) {
throw new RuntimeException("错误的时间值:" + time1);
}
if (arr2.length < 2) {
throw new RuntimeException("错误的时间值:" + time2);
}
int h1 = Integer.parseInt(arr1[0]);
int m1 = Integer.parseInt(arr1[1]);
int h2 = Integer.parseInt(arr2[0]);
int m2 = Integer.parseInt(arr2[1]);
int s1 = 0, s2 = 0;
if (arr1.length == 3) {
s1 = Integer.parseInt(arr1[2]);
}
if (arr2.length == 3) {
s2 = Integer.parseInt(arr2[2]);
}
if (h1 < 0 || h1 > 23 || m1 < 0 || m1 > 59 || s1 < 0 || s1 > 59) {
throw new RuntimeException("错误的时间值:" + time1);
}
if (h2 < 0 || h2 > 23 || m2 < 0 || m2 > 59 || s2 < 0 || s2 > 59) {
throw new RuntimeException("错误的时间值:" + time2);
}
if (h1 != h2) {
return h1 > h2 ? 1 : -1;
} else {
if (m1 == m2) {
if (s1 == s2) {
return 0;
} else {
return s1 > s2 ? 1 : -1;
}
} else {
return m1 > m2 ? 1 : -1;
}
}
}
/**
* 判断指定的字符串是否符合HH:mm:ss格式,并判断其数值是否在正常范围
*
* @param time
* @return
*/
public static boolean isTime(String time) {
String[] arr = time.split(":");
if (arr.length < 2) {
return false;
}
try {
int h = Integer.parseInt(arr[0]);
int m = Integer.parseInt(arr[1]);
int s = 0;
if (arr.length == 3) {
s = Integer.parseInt(arr[2]);
}
if (h < 0 || h > 23 || m < 0 || m > 59 || s < 0 || s > 59) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 判断指定的字符串是否符合yyyy:MM:ss格式,但判断其数据值范围是否正常
*
* @param date
* @return
*/
public static boolean isDate(String date) {
String[] arr = date.split("-");
if (arr.length < 3) {
return false;
}
try {
int y = Integer.parseInt(arr[0]);
int m = Integer.parseInt(arr[1]);
int d = Integer.parseInt(arr[2]);
if (y < 0 || m > 12 || m < 0 || d < 0 || d > 31) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 判断指定日期是否是周末
*
* @param date
* @return
*/
public static boolean isWeekend(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int t = cal.get(Calendar.DAY_OF_WEEK);
if (t == Calendar.SATURDAY || t == Calendar.SUNDAY) {
return true;
}
return false;
}
/**
* 以yyyy-MM-dd解析指定字符串,并判断相应的日期是否是周末
*
* @param str
* @return
*/
public static boolean isWeekend(String str) {
return isWeekend(parse(str));
}
/**
* 将obj转换成Date
* @param obj
* @return
*/
public static Date getDate(Object obj){
Date date =null;
try{
try{
date = (Date)obj;
}catch (Exception e) {
try{
date =parseDateTime(obj.toString());
}catch (Exception e1) {
// TODO: handle exception
}
}
if(date==null){
try{
DateTime dateTime = (DateTime)obj;
date = new Date(dateTime.getMillis());
}catch (Exception e) {
throw new RuntimeException(obj+"非标准时间格式");
}
}
}catch (Exception e) {
}
return date;
}
/**
* 将obj转换成getDateTime
* @param obj
* @return
*/
public static DateTime getDateTime(Object obj){
DateTime dateTime =null;
try{
try{
dateTime = (DateTime)obj;
}catch (Exception e) {
}
if(dateTime==null){
try{
Date date=null;
try{
date = (Date)obj;
}catch (Exception e) {
try{
date =parseDateTime(obj.toString());
}catch (Exception e1) {
// TODO: handle exception
}
}
dateTime = new DateTime(date.getTime());
}catch (Exception e) {
throw new RuntimeException(obj+"非标准时间格式");
}
}
}catch (Exception e) {
}
return dateTime;
}
/**
* 以yyyy-MM-dd解析指定字符串,返回相应java.util.Date对象
*
* @param str
* @return
*/
public static Date parse(String str) {
if (StringUtil.isEmpty(str)) {
return null;
}
try {
return new SimpleDateFormat(Format_Date).parse(str);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 按指定格式解析字符串,并返回相应的java.util.Date对象
*
* @param str
* @param format
* @return
*/
public static Date parse(String str, String format) {
if (StringUtil.isEmpty(str)) {
return null;
}
try {
SimpleDateFormat t = new SimpleDateFormat(format);
return t.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
return null;
}
}
/**
* 以yyyy-MM-dd HH:mm:ss格式解析字符串,并返回相应的java.util.Date对象
*
* @param str
* @return
*/
public static Date parseDateTime(String str) {
if (StringUtil.isEmpty(str)) {
return null;
}
if (str.length() <= 10) {
return parse(str);
}
try {
return new SimpleDateFormat(Format_DateTime).parse(str);
} catch (ParseException e) {
// e.printStackTrace();
return null;
}
}
/**
* 以指定格式解析字符串,并返回相应的java.util.Date对象
*
* @param str
* @param format
* @return
*/
public static Date parseDateTime(String str, String format) {
if (StringUtil.isEmpty(str)) {
return null;
}
try {
SimpleDateFormat t = new SimpleDateFormat(format);
return t.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
return null;
}
}
/**
* 日期date上加count分钟,count为负表示减
*/
public static Date addMinute(Date date, int count) {
return new Date(date.getTime() + 60000L * count);
}
/**
* 日期date上加count小时,count为负表示减
*/
public static Date addHour(Date date, int count) {
return new Date(date.getTime() + 3600000L * count);
}
/**
* 日期date上加count天,count为负表示减
*/
public static Date addDay(Date date, int count) {
return new Date(date.getTime() + 86400000L * count);
}
/**
* 日期date上加count星期,count为负表示减
*/
public static Date addWeek(Date date, int count) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.WEEK_OF_YEAR, count);
return c.getTime();
}
/**
* 日期date上加count月,count为负表示减
*/
public static Date addMonth(Date date, int count) {
/* ${_ZVING_LICENSE_CODE_} */
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, count);
return c.getTime();
}
/**
* 日期date上加count年,count为负表示减
*/
public static Date addYear(Date date, int count) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.YEAR, count);
return c.getTime();
}
/**
* 人性化显示时间日期,date格式为:yyyy-MM-dd HH:mm:ss
*
* @param date
* @return
*/
public static String toDisplayDateTime(String date) {
if (StringUtil.isEmpty(date)) {
return null;
}
try {
if (isDate(date)) {
return toDisplayDateTime(parse(date));
} else {
SimpleDateFormat t = new SimpleDateFormat(Format_DateTime);
Date d = t.parse(date);
return toDisplayDateTime(d);
}
} catch (ParseException e) {
e.printStackTrace();
return "不是标准格式时间!";
}
}
/**
* 人性化显示时间日期
*
* @param date
* @return
*/
public static String toDisplayDateTime(Date date) {
long minite = (System.currentTimeMillis() - date.getTime()) / 60000L;
if (minite < 60) {
return toString(date, "yyyy-MM-dd") + " " + minite + "分钟前";
}
if (minite < 60 * 24) {
return toString(date, "yyyy-MM-dd") + " " + minite / 60L + "小时前";
} else {
return toString(date, "yyyy-MM-dd") + " " + minite / 1440L + "天前";
}
}
public static String convertChineseNumber(String strDate) {
strDate = StringUtil.replaceEx(strDate, "一十一", "11");
strDate = StringUtil.replaceEx(strDate, "一十二", "12");
strDate = StringUtil.replaceEx(strDate, "一十三", "13");
strDate = StringUtil.replaceEx(strDate, "一十四", "14");
strDate = StringUtil.replaceEx(strDate, "一十五", "15");
strDate = StringUtil.replaceEx(strDate, "一十六", "16");
strDate = StringUtil.replaceEx(strDate, "一十七", "17");
strDate = StringUtil.replaceEx(strDate, "一十八", "18");
strDate = StringUtil.replaceEx(strDate, "一十九", "19");
strDate = StringUtil.replaceEx(strDate, "二十一", "21");
strDate = StringUtil.replaceEx(strDate, "二十二", "22");
strDate = StringUtil.replaceEx(strDate, "二十三", "23");
strDate = StringUtil.replaceEx(strDate, "二十四", "24");
strDate = StringUtil.replaceEx(strDate, "二十五", "25");
strDate = StringUtil.replaceEx(strDate, "二十六", "26");
strDate = StringUtil.replaceEx(strDate, "二十七", "27");
strDate = StringUtil.replaceEx(strDate, "二十八", "28");
strDate = StringUtil.replaceEx(strDate, "二十九", "29");
strDate = StringUtil.replaceEx(strDate, "十一", "11");
strDate = StringUtil.replaceEx(strDate, "十二", "12");
strDate = StringUtil.replaceEx(strDate, "十三", "13");
strDate = StringUtil.replaceEx(strDate, "十四", "14");
strDate = StringUtil.replaceEx(strDate, "十五", "15");
strDate = StringUtil.replaceEx(strDate, "十六", "16");
strDate = StringUtil.replaceEx(strDate, "十七", "17");
strDate = StringUtil.replaceEx(strDate, "十八", "18");
strDate = StringUtil.replaceEx(strDate, "十九", "19");
strDate = StringUtil.replaceEx(strDate, "十", "10");
strDate = StringUtil.replaceEx(strDate, "二十", "20");
strDate = StringUtil.replaceEx(strDate, "三十", "20");
strDate = StringUtil.replaceEx(strDate, "三十一", "31");
strDate = StringUtil.replaceEx(strDate, "零", "0");
strDate = StringUtil.replaceEx(strDate, "○", "0");
strDate = StringUtil.replaceEx(strDate, "一", "1");
strDate = StringUtil.replaceEx(strDate, "二", "2");
strDate = StringUtil.replaceEx(strDate, "三", "3");
strDate = StringUtil.replaceEx(strDate, "四", "4");
strDate = StringUtil.replaceEx(strDate, "五", "5");
strDate = StringUtil.replaceEx(strDate, "六", "6");
strDate = StringUtil.replaceEx(strDate, "七", "7");
strDate = StringUtil.replaceEx(strDate, "八", "8");
strDate = StringUtil.replaceEx(strDate, "九", "9");
return strDate;
}
/**
* 传入秒数 返回 xx:xx:xx这种时间格式
* @param second
* @return
*/
public static String getTimeStr(long second) {
String timsStr = "";
String hourStr = String.valueOf(second / (60 * 60));
long second1 = second % 3600;
if (hourStr.length() == 1) {
hourStr = "0" + hourStr;
}
String minite = String.valueOf(second1 / 60);
if (minite.length() == 1) {
minite = "0" + minite;
}
String second2 = String.valueOf(second1 % 60);
if (second2.length() == 1) {
second2 = "0" + second2;
}
timsStr = hourStr + ":" +minite + ":" + second2;
return timsStr;
}
public static String getFormatTimeStr(String timeStr){
String str = "";
if(timeStr.length() != 0) {
str = timeStr.replaceAll(":","'");
}
return str;
}
public static String getTotalSecond(String dateStr){
String result = "";
if(StringUtil.isNotEmpty(dateStr)&&dateStr.indexOf(":")>-1){
String[] arr = dateStr.split(":");
Long hour = Long.valueOf(arr[0])*60*60;
Long min = Long.valueOf(arr[1])*60;
Long second = Long.valueOf(arr[2]);
result = String.valueOf(hour+min+second);
}else{
result = "0";
}
return result;
}
/**
* 计算2个时间戳日期的天数差 date2 -date1
* @param date1
* @param date2
* @return
* @throws ParseException
*/
public static int getDaysDifference(Long date1, Long date2) throws ParseException{
Date d1 = new Date(date1);
Date d2 = new Date(date2);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
d1 = sdf.parse(sdf.format(d1));
d2 = sdf.parse(sdf.format(d2));
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
Long time1 = cal.getTimeInMillis();
cal.setTime(d2);
Long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
public static void main(String []s){
Date datemie = new Date();
System.out.println(getDateTime(datemie));
}
/**
* 得到一天的开始时间
* @param date
* @return
*/
public static Date getStartTimeOfDay(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date start = calendar.getTime();
return start;
}
/**
* 得到一天的结束时间
* @param date
* @return
*/
public static Date getEndTimeOfDay(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
Date end = calendar.getTime();
return end;
}
/**
* 判断当前时间距离第二天凌晨的秒数
*
* @return 返回值单位为[s:秒]
*/
public static Long getSecondsNextEarlyMorning() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
}
/*
得到一天的开始时间
*/
public static Date getStartTime(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date start = calendar.getTime();
return date;
}
/*
得到一天的结束时间
*/
public static Date getEndTime(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.add(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.SECOND, -1);
Date end = calendar.getTime();
return end;
}
public static String getTimeStrByFormat(Long timestamp, String format) {
if (StringUtil.isEmpty(format)) {
format = Format_DateTime;
}
if (timestamp == null || timestamp.longValue() == 0) {
timestamp = System.currentTimeMillis();
}
SimpleDateFormat sformat = new SimpleDateFormat(format);
String timeText = sformat.format(timestamp);
return timeText;
}
public static String getDateStrByNowByFormat(Date date,String format) {
if (date == null) {
return null;
}
if (StringUtils.isBlank(format)){
format = Format_DateTime;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
String result = sdf.format(date);
return result;
}
public static String getDateStrByNowByFormat(Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(Format_DateTime);
String result = sdf.format(date);
return result;
}
/**
* 获取过去第几天的日期
*
* @param past
* @return
*/
public static String getPastDate(int past, Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - past);
Date day = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat(Format_Date);
String result = sdf.format(day);
return result;
}
public static String getYmdStrByNow(Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(Format_Date);
String result = sdf.format(date);
return result;
}
//获取某段时间内的所有日期
public static List<String> findDates(String startDate, String endDate) {
Date dStart = parse(startDate);
Date dEnd = parse(endDate);
Calendar cStart = Calendar.getInstance();
cStart.setTime(dStart);
List dateList = new ArrayList();
startDate = getYmdStrByNow(dStart);
dateList.add(startDate);
while (dEnd.after(cStart.getTime())) {
cStart.add(Calendar.DAY_OF_MONTH, 1);
Date current = cStart.getTime();
dateList.add(toString(current));
}
return dateList;
}
public static String getDateStrBynowFormat() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(Format_DateTime1);
String result = sdf.format(date);
return result;
}
/**
* 获取指定日期前一天日期
*/
public static String getBefore(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(Format_Date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
String before = sdf.format(calendar.getTime());
return before;
}
}
第二类:
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.util.Calendar.DAY_OF_MONTH;
public class TimeUtils {
public static final String DEFAULT_YYYYMMDD_HHMMSS = "yyyy/MM/dd HH:mm:ss";
public static final String DEFAULT_YYYYMMDD_HHMMSS_SSS = "yyyy/MM/dd HH:mm:ss.SSS";
public static final String YYYYMMDD_HHMMSS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYYMMDD_HHMMSS_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
public static final String YYYYMMDD_HH = "yyyy-MM-dd HH";
public static final String YYYYMMDD_HH1 = "yyyyMMddHH";
public static final String YYYYMMDD = "yyyy-MM-dd";
public static final String YYYYMMDD2 = "yyyy年MM月dd日";
public static final String YYYYMMDD3 = "yyyy/MM/dd";
public static final String YYYYMMDD4 = "yyyy/MM";
public static final String YYYYMMDD5 = "yyyyMMdd";
public static final String YYYYMMDD_HHMMSS2 = "yyyyMMddHHmmss";
public static final String YYYYMMDD_HHMMSS_SSS2 = "yyyyMMddHHmmssSSS";
public static final String YYYYMMDD_HHMMSS3 = "yyyy年MM月dd日HH时mm分ss秒";
public static final String YYYYMMDD_HHMMSS_SSS3 = "yyyy年MM月dd日HH时mm分ss秒SSS毫秒";
public static final String DAY = "day";
public static final String HOUR = "hour";
public static final String MINUTE = "minute";
public static final String SECOND = "second";
public static final String MILLIS = "millis";
/**
* 新浪微博格式的处理器
*/
private static final SimpleDateFormat sinaSDF = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy", Locale.US);
public static final String[] WEEK_DAYS = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
public static String[] DEFAULT_PATTERNS = {
DEFAULT_YYYYMMDD_HHMMSS,
DEFAULT_YYYYMMDD_HHMMSS_SSS,
YYYYMMDD_HHMMSS_SSS,
YYYYMMDD_HHMMSS_SSS2,
YYYYMMDD_HHMMSS_SSS3,
YYYYMMDD_HHMMSS,
YYYYMMDD_HHMMSS2,
YYYYMMDD_HHMMSS3,
YYYYMMDD3,
YYYYMMDD,
YYYYMMDD_HH1,
YYYYMMDD_HH,
YYYYMMDD2,
YYYYMMDD4,
YYYYMMDD5
};
public static String[] TIME_PATTERNS = {
DEFAULT_YYYYMMDD_HHMMSS,
DEFAULT_YYYYMMDD_HHMMSS_SSS,
YYYYMMDD_HHMMSS_SSS,
YYYYMMDD_HHMMSS_SSS2,
YYYYMMDD_HHMMSS_SSS3,
YYYYMMDD_HHMMSS,
YYYYMMDD_HHMMSS2,
YYYYMMDD_HHMMSS3,
YYYYMMDD_HH1,
YYYYMMDD_HH
};
public static String[] DATE_PATTERNS = {
YYYYMMDD3,
YYYYMMDD,
YYYYMMDD2,
YYYYMMDD4,
YYYYMMDD5
};
/**
* 判断传入的字符串是否属于新浪微博格式(Sun Nov 14 12:19:13 +0800 2021)<BR>
*
* @param inputStr 输入的字符串
* @return <ul>
* <li>true - 属于</li>
* <li>false - 不属于</li>
* </ul>
*/
public static boolean isSinaTime(String inputStr) {
if (StringUtils.isEmpty(inputStr)) {
return false;
}
sinaSDF.setLenient(false);
//设置解析日期格式是否严格解析日期
ParsePosition pos = new ParsePosition(0);
sinaSDF.parse(inputStr, pos);
if (pos.getIndex() == inputStr.length()) {
return true;
}
return false;
}
/**
* 判断传入的字符串是是否属于时间<BR>
*
* @param inputStr 输入的字符串
* @return <ul>
* <li>true - 属于时间</li>
* <li>false - 不属于时间</li>
* </ul>
*/
public static boolean isTimeString(String inputStr) {
if (StringUtils.isEmpty(inputStr)) {
return false;
}
SimpleDateFormat df = new SimpleDateFormat();
final String[] localDateFormats = TIME_PATTERNS;
for (String pattern : localDateFormats) {
df.applyPattern(pattern);
//设置解析日期格式是否严格解析日期
df.setLenient(false);
ParsePosition pos = new ParsePosition(0);
df.parse(inputStr, pos);
if (pos.getIndex() == inputStr.length()) {
return true;
}
}
return false;
}
/**
* 判断传入的字符串是是否属于日期<BR>
*
* @param inputStr 输入的字符串
* @return <ul>
* <li>true - 属于日期</li>
* <li>false - 不属于日期</li>
* </ul>
*/
public static boolean isDateString(String inputStr) {
if (StringUtils.isEmpty(inputStr)) {
return false;
}
if (!isTimeString(inputStr)) {
SimpleDateFormat df = new SimpleDateFormat();
final String[] localDateFormats = DATE_PATTERNS;
for (String pattern : localDateFormats) {
df.applyPattern(pattern);
//设置解析日期格式是否严格解析日期
df.setLenient(false);
ParsePosition pos = new ParsePosition(0);
df.parse(inputStr, pos);
if (pos.getIndex() == inputStr.length()) {
return true;
}
}
}
return false;
}
/**
* 将字符串日期转成另外一种格式的字符串日期
*
* @param inputDate 输入时间
* @return
*/
public static String stringToString(String inputDate) {
return dateToString(stringToDate(inputDate), DEFAULT_YYYYMMDD_HHMMSS);
}
/**
* 将字符串日期转成另外一种格式的字符串日期
*
* @param inputDate 输入时间
* @param outputRegex 返回的时间格式
* @return
*/
public static String stringToString(String inputDate, String outputRegex) {
return dateToString(stringToDate(inputDate), outputRegex);
}
/**
* 将字符串日期转成另外一种格式的字符串日期
*
* @param inputRegex 输入时间格式
* @param inputDate 输入时间
* @param outputRegex 返回的时间格式
* @return
*/
public static String stringToString(String inputRegex, String inputDate, String outputRegex) {
return dateToString(stringToDate(inputDate, inputRegex), outputRegex);
}
/**
* 将输入的时间转成Date类型
*
* @param inputDate 待转换时间
* @return
*/
public static Date stringToDate(String inputDate) {
return stringToDate(inputDate, null);
}
/**
* 将字符串转成日期对象
*
* @param dateString
* @param dateFormat
* @return
*/
public static Date stringToDate(String dateString, String dateFormat) {
if (StringUtils.isEmpty(dateString)) {
return null;
}
return parseDate(dateString, dateFormat);
}
/**
* 将日期转为String对象
*
* @param date
* @return
*/
public static String dateToString(Date date) {
return dateToString(date, DEFAULT_YYYYMMDD_HHMMSS);
}
/**
* 将日期转为String对象
*
* @param date 时间
* @param timeRegex
* @return
*/
public static String dateToString(Date date, String timeRegex) {
Assert.isTrue(date != null, "传入的时间不能为空!");
timeRegex = StringUtils.isEmpty(timeRegex) ? DEFAULT_YYYYMMDD_HHMMSS : timeRegex;
return new SimpleDateFormat(timeRegex).format(date);
}
/**
* 将日期转为String对象
*
* @param dateLong 时间
* @param
* @return
*/
public static String longToString(long dateLong) {
return longToString(dateLong, null);
}
public static String longToString(long dateLong, String dateFormat) {
return dateToString(new Date(dateLong), dateFormat);
}
/**
* 得到当天的日期
*
* @return 返回当天的日期
*/
public static String getCurrentDate() {
return getCurrentDate(null);
}
/**
* 得到当天的日期
*
* @return 返回当天的日期
*/
public static String getCurrentDate(String dateFormat) {
return dateToString(new Date(), dateFormat);
}
/**
* 获取当前日期几天前的日期
*
* @param day 之前(负数)或之后(正数)的天数
* @return
*/
public static String dateBefOrAft(int day) {
return dateBefOrAft(day, DEFAULT_YYYYMMDD_HHMMSS);
}
/**
* 获取当前日期几天前的日期
*
* @param day 之前(负数)或之后(正数)的天数
* @return
*/
public static String dateBefOrAft(int day, String returnRegex) {
return dateBefOrAft(getCurrentDate(returnRegex), day, returnRegex);
}
/**
* 获取几天前的日期
*
* @param day 之前(负数)或之后(正数)的天数
* @return
*/
public static String dateBefOrAft(String date, int day, String returnRegex) {
return dateBefOrAft(date, day, null, returnRegex);
}
/**
* 获取几天前的日期
*
* @param day 之前(负数)或之后(正数)的天数
* @return
*/
public static String dateBefOrAft(String date, int day, String timeRegex, String returnRegex) {
returnRegex = StringUtils.isEmpty(returnRegex) ? timeRegex : returnRegex;
return dateBefOrAft(stringToDate(date, timeRegex), day, returnRegex);
}
/**
* 获取某日期的几天前的日期
*
* @param date 日期
* @param day 之前(负数)或之后(正数)的天数
* @return
*/
public static String dateBefOrAft(Date date, int day) {
return dateBefOrAft(date, day, DEFAULT_YYYYMMDD_HHMMSS);
}
/**
* 获取某日期的几天前的日期
*
* @param date 日期
* @param day 之前(负数)或之后(正数)的天数
* @return
*/
public static String dateBefOrAft(Date date, int day, String returnRegex) {
return dateToString(befOrAft(date, day, DAY_OF_MONTH), returnRegex);
}
/**
* 获取时间前/后几小时的时间
*
* @param hour 时间
* @param hour 之前(负数)或之后(正数)的小时数
* @return
*/
public static String hourDefOrAft(int hour) {
return hourDefOrAft(hour, DEFAULT_YYYYMMDD_HHMMSS);
}
/**
* 获取时间前/后几小时的时间
*
* @param hour 之前(负数)或之后(正数)的小时数
* @return
*/
public static String hourDefOrAft(int hour, String timeRegex) {
return hourDefOrAft(new Date(), hour, timeRegex);
}
/**
* 获取时间前/后几小时的时间
*
* @param date 时间
* @param hour 之前(负数)或之后(正数)的小时数
* @param timeRegex
* @return
*/
public static String hourDefOrAft(String date, int hour, String timeRegex) {
return hourDefOrAft(date, hour, null, timeRegex);
}
/**
* 获取时间前/后几小时的时间
*
* @param date 时间
* @param hour 之前(负数)或之后(正数)的小时数
* @param timeRegex
* @return
*/
public static String hourDefOrAft(String date, int hour, String timeRegex, String returnRegex) {
timeRegex = StringUtils.isEmpty(timeRegex) ? returnRegex : timeRegex;
return hourDefOrAft(stringToDate(date, timeRegex), hour, returnRegex);
}
/**
* 获取时间前/后几小时的时间
*
* @param date 时间
* @param hour 之前(负数)或之后(正数)的小时数
* @param timeRegex
* @return
*/
public static String hourDefOrAft(Date date, int hour, String timeRegex) {
return dateToString(befOrAft(date, hour, Calendar.HOUR_OF_DAY), timeRegex);
}
/**
* 获取时间前/后几天的日期
*
* @param num 如果要获得前几天日期,该参数为负数;如果要获得后几天日期,该参数为正数
* @return
*/
public static Date befOrAft(Date specifiedDate, int num, final int field) {
Calendar cal = Calendar.getInstance();
cal.setTime(specifiedDate);
cal.add(field, num);
return cal.getTime();
}
/**
* 获取两个日期之间相隔的天数
*
* @param startDate
* @return
*/
public static int getNumDay(String startDate, String endDate) {
return getNumDay(stringToDate(startDate), stringToDate(endDate));
}
/**
* 获取两个日期之间相隔的天数
*
* @param startDate
* @return
*/
public static int getNumDay(Date startDate, Date endDate) {
return (int) getNumTime(startDate, endDate, DAY);
}
/**
* 获取两个日期之间相隔的小时数
*
* @param startDate
* @return
*/
public static int getNumHour(String startDate, String endDate) {
return getNumHour(stringToDate(startDate), stringToDate(endDate));
}
/**
* 获取两个日期之间相隔的小时数
*
* @param startDate
* @return
*/
public static int getNumHour(Date startDate, Date endDate) {
return (int) (getNumTime(startDate, endDate, HOUR));
}
/**
* 获取两个时间之间相隔的分钟数
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return
*/
public static int getNumMinutes(String startDate, String endDate) {
return getNumMinutes(stringToDate(startDate), stringToDate(endDate));
}
/**
* 获取两个时间之间相隔的分钟数
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return
*/
public static int getNumMinutes(Date startDate, Date endDate) {
return (int) (getNumTime(startDate, endDate, MINUTE));
}
/**
* 获取两个时间之间相隔的秒数
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return
*/
public static long getNumSec(String startDate, String endDate) {
return getNumSec(stringToDate(startDate), stringToDate(endDate));
}
/**
* 获取两个时间之间相隔的秒数
*
* @param startDate 开始时间
* @param endDate 结束时间
* @return
*/
public static long getNumSec(Date startDate, Date endDate) {
return getNumTime(startDate, endDate, MINUTE);
}
/**
* 获取两个时间之间相隔的毫秒数
*
* @param endDate
* @param startDate
* @return
*/
public static Long getNumMs(String startDate, String endDate) {
return getNumMs(stringToDate(startDate), stringToDate(endDate));
}
/**
* 获取两个时间之间相隔的毫秒数
*
* @param endDate
* @param startDate
* @return
*/
public static Long getNumMs(Date startDate, Date endDate) {
return getNumTime(startDate, endDate, MILLIS);
}
private static long getNumTime(Date startDate, Date endDate, String type) {
endDate = endDate == null ? new Date() : endDate;
startDate = startDate == null ? new Date() : startDate;
//一天的毫秒数
long nd = 1000 * 24 * 60 * 60;
//一小时的毫秒数
long nh = 1000 * 60 * 60;
//一分钟的毫秒数
long nm = 1000 * 60;
//一秒钟的毫秒数
long ns = 1000;
long num = 0L;
long diff = endDate.getTime() - startDate.getTime();
switch (type) {
case DAY:
num = diff / nd;
break;
case HOUR:
num = diff % nd / nh;
break;
case MINUTE:
num = diff % nd % nh / nm;
break;
case SECOND:
num = diff % nd % nh % nm / ns;
break;
case MILLIS:
num = diff;
break;
default:
break;
}
return num;
}
/**
* 判断某一时间是否在一个区间内
*
* @param timeArea 时间区间,如[10:00,20:00]
* @param curTime 需要判断的时间 如15:00
* @return boolean
*/
public static boolean insideTimeRange(String timeArea, String curTime) {
return insideTimeRange(timeArea, curTime, DEFAULT_YYYYMMDD_HHMMSS);
}
/**
* 判断某一时间是否在一个区间内
*
* @param timeArea 时间区间,如[10:00,20:00]
* @param curTime 需要判断的时间 如15:00
* @return boolean
*/
public static boolean insideTimeRange(String timeArea, String curTime, String timeRegex) {
return insideTimeRange(timeArea, curTime, timeRegex, ",");
}
/**
* 判断某一时间是否在一个区间内
*
* @param timeArea 时间区间,如[10:00,20:00]
* @param curTime 需要判断的时间 如10:00
* @return boolean
*/
public static boolean insideTimeRange(String timeArea, String curTime, String timeRegex, String split) {
//1.检查传来的时间是否符合规则
Assert.isTrue(timeArea != null && timeArea.contains(split), "可用时间段格式不符合");
Assert.isTrue(curTime != null, "当前时间格式不符合");
String[] times = timeArea.split(",");
SimpleDateFormat sdf = new SimpleDateFormat(timeRegex);
try {
//2.获取起始时间、截止时间
long now = sdf.parse(curTime).getTime();
long start = sdf.parse(times[0]).getTime();
long end = sdf.parse(times[1]).getTime();
if (now >= start && now <= end) {
return true;
} else {
return false;
}
} catch (ParseException e) {
throw new IllegalArgumentException("判断时间段报错:" + timeArea + e);
}
}
/**
* 判断时间大小
*
* @param maxDate
* @param minDate
* @return
*/
public static boolean isMaxDate(String maxDate, String minDate) {
return isMaxDate(stringToDate(maxDate), stringToDate(minDate));
}
/**
* 判断时间大小
*
* @param maxDate
* @param minDate
* @return
*/
public static boolean isMaxDate(Date maxDate, Date minDate) {
if (maxDate.before(minDate)) {
return false;
}
return true;
}
/**
* 获取两个日期之间的所有日期
*
* @param startTime
* @param endTime
* @return
* @throws ParseException
*/
public static List<String> getDateList(String startTime, String endTime) {
return getDateList(startTime, endTime, YYYYMMDD3);
}
public static List<String> getDateList(String startTime, String endTime, String returnFormat) {
return getDateList(startTime, endTime, returnFormat, true);
}
/**
* 获取两个日期之间的所有日期
*
* @param startTime 开始时间
* @param endTime 结束时间
* @param allowOverNow 是否允许超过当前时间
* @return List
*/
public static List<String> getDateList(String startTime, String endTime, String returnFormat, boolean allowOverNow) {
return getDateList(startTime, endTime, null, returnFormat, allowOverNow, true);
}
/**
* 获取两个日期之间的所有日期
*
* @param startTime 开始时间
* @param endTime 结束时间
* @param allowOverNow 是否允许超过当前时间
* @param containEndDay 是否允许包含结束时间
* @return List
*/
public static List<String> getDateList(String startTime, String endTime, String dateFormat, String returnFormat, boolean allowOverNow, final boolean containEndDay) {
if (StringUtils.isEmpty(startTime) || (StringUtils.isEmpty(endTime))) {
return null;
}
Date startDate = stringToDate(startTime, dateFormat);
Date endDate = stringToDate(endTime, dateFormat);
//不允许结束时间超过当前时间
if (!allowOverNow && endDate.getTime() > System.currentTimeMillis()) {
endDate = new Date();
}
return findTimePeriod(startDate, endDate, DAY_OF_MONTH, returnFormat, containEndDay);
}
/**
* 获取传入时间到当前时间之间的月份
*
* @param beginDay 开始时间
* @return 返回时间段的日期格式为yyyy/MM
* @throws Exception
*/
public static List<String> findMonths(String beginDay) {
return findMonths(beginDay, getCurrentDate(YYYYMMDD4));
}
/**
* 获取传入时间到当前时间之间的月份
*
* @param beginDay 开始时间
* @return 返回时间段的日期格式为yyyy/MM
* @throws Exception
*/
public static List<String> findMonths(String beginDay, String endDay) {
return findMonths(beginDay, endDay, YYYYMMDD4, true);
}
/**
* 获取传入时间到当前时间之间的月份
*
* @param beginDay 开始时间
* @param returnRegex 返回日期格式 形如yyyy/MM
* @param desc 是否倒序排序
* @return 返回时间段的日期格式为yyyy/MM/dd
* @throws Exception
*/
public static List<String> findMonths(String beginDay, String endDay, String returnRegex, final boolean desc) {
return findMonths(beginDay, endDay, returnRegex, desc, true);
}
/**
* 获取传入时间到当前时间之间的月份
*
* @param beginDay 开始时间
* @param endDay 结束时间
* @param returnRegex 返回日期格式 形如yyyy/MM
* @param desc 是否倒序排序
* @param containEndDay 是否允许包含结束时间
* @return 返回时间段的日期格式为yyyy/MM/dd
*/
public static List<String> findMonths(String beginDay, String endDay, String returnRegex, final boolean desc, final boolean containEndDay) {
return findMonths(beginDay, endDay, null, returnRegex, desc, containEndDay);
}
/**
* 获取传入时间到当前时间之间的月份
*
* @param beginDay 开始时间
* @param endDay 结束时间
* @param timeRegex 输入时间的格式
* @param returnFormat 返回日期格式 形如yyyy/MM
* @param desc 是否倒序排序
* @param containEndDay 是否允许包含结束时间
* @return 返回时间段的日期格式为yyyy/MM/dd
*/
public static List<String> findMonths(String beginDay, String endDay, String timeRegex, String returnFormat, final boolean desc, final boolean containEndDay) {
//定义开始日期
Date startDay = stringToDate(beginDay, timeRegex);
//定义结束日期
Date now = stringToDate(endDay, timeRegex);
List<String> months = findTimePeriod(startDay, now, Calendar.MONTH, returnFormat, containEndDay);
//时间排序
sortTime(months, desc);
return months;
}
/**
* 获取一个时间段内的月份、日期、年份、分钟等
*
* @param startDay
* @param endDay
* @param field 分段标志:月份、天、年
* @param timeRegex
* @return
*/
public static List<String> findTimePeriod(Date startDay, Date endDay, int field, String timeRegex, final boolean containEndDay) {
List<String> dateList = new ArrayList<>();
SimpleDateFormat dateFormat = new SimpleDateFormat(timeRegex);
//定义日期实例
Calendar dd = Calendar.getInstance();
//设置日期起始时间
dd.setTime(startDay);
//判断是否需要包含结束日期
if (containEndDay) {
endDay = befOrAft(endDay, 1, DAY_OF_MONTH);
}
//判断是否到结束日期
while (dd.getTime().before(endDay)) {
dateList.add(dateFormat.format(dd.getTime()));//日期结果
dd.add(field, 1);//进行当前日期月份加1
}
return dateList;
}
/**
* 获取开始时间到今天的时间区间,分割成20个区间
*
* @param beginDay 开始时间
* @return
*/
public static List<String> findDatesRange(String beginDay) {
return findDatesRange(beginDay, getCurrentDate());
}
/**
* 获取开始时间和结束时间之间的时间区间,分割成20个区间
*
* @param beginDay 开始时间
* @param endDay 开始时间
* @return
*/
public static List<String> findDatesRange(String beginDay, String endDay) {
return findDatesRange(beginDay, endDay, YYYYMMDD3);
}
/**
* 获取开始时间和结束时间之间的时间区间,分割成20个区间
*
* @param beginDay 开始时间
* @param endDay 结束时间
* @param returnFormat 返回时间段的日期格式。 默认yyyy/MM/dd
* @return
*/
public static List<String> findDatesRange(String beginDay, String endDay, String returnFormat) {
return findDatesRange(beginDay, endDay, "->", returnFormat);
}
/**
* 获取开始时间和结束时间之间的时间区间,分割成20个区间
*
* @param beginDay 开始时间
* @param endDay 结束时间
* @param range 区间数
* @param returnFormat 返回时间段的日期格式。 默认yyyy/MM/dd
* @return List
*/
public static List<String> findDatesRange(String beginDay, String endDay, int range, String returnFormat) {
return findDatesRange(beginDay, endDay, "->", range, returnFormat);
}
/**
* 获取n个开始时间和结束时间之间的时间区间,默认分割成15个区间
*
* @param beginDay 开始时间
* @param endDay 开始时间
* @param symbol 符号
* @param returnFormat 返回时间段的日期格式。 默认yyyy/MM/dd
* @return
* @throws Exception
*/
public static List<String> findDatesRange(String beginDay, String endDay, String symbol, String returnFormat) {
return findDatesRange(stringToDate(beginDay), stringToDate(endDay), symbol, returnFormat);
}
/**
* 获取开始时间和结束时间之间的时间区间,分割成20个区间
*
* @param beginDay 开始时间
* @param endDay 结束时间
* @param range 区间数
* @param returnFormat 返回时间段的日期格式。 默认yyyy/MM/dd
* @return List
*/
public static List<String> findDatesRange(String beginDay, String endDay, String symbol, int range, String returnFormat) {
return findDatesRange(stringToDate(beginDay), stringToDate(endDay), symbol, range, returnFormat);
}
/**
* 获取开始时间和结束时间之间的时间区间,分割成20个区间
*
* @param beginDate 开始时间
* @param endDate 结束时间
* @param symbol 符号
* @param returnFormat 返回时间段的日期格式。 默认yyyy/MM/dd
* @return List
*/
public static List<String> findDatesRange(Date beginDate, Date endDate, String symbol, String returnFormat) {
return findDatesRange(beginDate, endDate, symbol, 15, returnFormat);
}
/**
* 获取n个开始时间和结束时间之间的时间区间,默认分割成15个区间
*
* @param beginDate 开始时间
* @param endDate 结束时间
* @param symbol 连接符号
* @param range 区间数
* @param returnFormat 返回时间段的日期格式。 默认yyyy/MM/dd
* @return List
*/
public static List<String> findDatesRange(Date beginDate, Date endDate, String symbol, int range, String returnFormat) {
Assert.isTrue(range != 0, "findDatesRange执行失败,传入的时间区间不能等于0!");
Assert.isTrue(beginDate != null && endDate != null, "findDatesRange执行失败,传入的开始时间或结束时间不能为空!");
Assert.isTrue(beginDate.before(endDate), "findDatesRange执行失败,开始时间不能大于结束时间!");
int defferentDays = getNumDay(beginDate, endDate);
int count = 0;
int intervalTime = defferentDays / range;
int lastIntervalTime = defferentDays % range; //最后一个时间区间,
List<String> result = new ArrayList<>();
SimpleDateFormat sdf = returnFormat != null ? new SimpleDateFormat(returnFormat) : new SimpleDateFormat(YYYYMMDD3);
Calendar cal = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
cal.setTime(beginDate);
String rangeStartTime = dateToString(beginDate, returnFormat);
while (true) {
//当
if (intervalTime == 0) {
result.add(rangeStartTime + symbol + sdf.format(endDate));
break;
}
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
cal.add(Calendar.DAY_OF_MONTH, count == range - 1 && lastIntervalTime != 0 ? lastIntervalTime + intervalTime : intervalTime - 1);
// 测试此日期是否在指定日期之后
if (endDate.after(cal.getTime()) || endDate.equals(cal.getTime())) {
result.add(rangeStartTime + symbol + sdf.format(cal.getTime()));
//当前结束时间的后一天为下个区间的开始时间
rangeStartTime = dateBefOrAft(cal.getTime(), 1, returnFormat);
cal.add(Calendar.DAY_OF_MONTH, 1);
count++;
} else {
break;
}
}
return result;
}
/**
* 判断今天星期数
*
* @return
*/
public static String getWeekOfDate() {
return getWeekOfDate(new Date());
}
/**
* 判断星期数
*
* @param time
* @return
*/
public static String getWeekOfDate(String time) {
return getWeekOfDate(stringToDate(time));
}
/**
* 判断星期数
*
* @param date 时间
* @return
*/
public static String getWeekOfDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0) {
w = 0;
}
return WEEK_DAYS[w];
}
/**
* 获取本月的周末
*
* @return
*/
public static List<String> getCurMonthWeekdays() {
return getCurMonthWeekdays(YYYYMMDD3);
}
/**
* 获取本月的周末
*
* @return
*/
public static List<String> getCurMonthWeekdays(String timeRegex) {
Calendar cal = Calendar.getInstance();
return getWeekdays(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, timeRegex);
}
/**
* 获取某年某月的周末
*
* @param time
* @return
*/
public static List<String> getWeekdays(String time) {
return getWeekdays(time, YYYYMMDD3);
}
public static List<String> getWeekdays(String time, String timeRegex) {
Calendar cal = Calendar.getInstance();
cal.setTime(stringToDate(time));
return getWeekdays(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY) + 1, timeRegex);
}
/**
* 获取某年某月的周末
*
* @param year
* @param month
* @return
*/
public static List<String> getWeekdays(int year, int month) {
return getWeekdays(year, month, YYYYMMDD3);
}
/**
* 获取某年某月的周末
*
* @param year
* @param month
* @return
*/
public static List<String> getWeekdays(int year, int month, String timeRegex) {
SimpleDateFormat sdf = new SimpleDateFormat(timeRegex);
List<String> weekDayList = new ArrayList<>();
// 1.获得当前日期对象
Calendar cal = Calendar.getInstance();
// 2.清除信息
cal.clear();
//3.设置年、月
cal.set(Calendar.YEAR, year);
// 3.1 1月从0开始
cal.set(Calendar.MONTH, month - 1);
// 3.2 当月1号
cal.set(DAY_OF_MONTH, 1);
int count = cal.getActualMaximum(DAY_OF_MONTH);
for (int j = 1; j <= count; j++) {
//4. 判断是否是周末
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
weekDayList.add(sdf.format(cal.getTime()));
}
//5.增加一天
cal.add(DAY_OF_MONTH, 1);
}
return weekDayList;
}
/**
* 获取上个月的开始日期和结束日期时间戳
* @param index 0为开始时间 其他为结束时间
* @return
*/
public static Long getDayOfLastMonth(int index) {
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);
if (index == 0) {
//将小时至0
calendar.set(Calendar.HOUR_OF_DAY, 0);
//将分钟至0
calendar.set(Calendar.MINUTE, 0);
//将秒至0
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MONTH, month-1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
} else {
//将小时至23
calendar.set(Calendar.HOUR_OF_DAY, 23);
//将分钟至59
calendar.set(Calendar.MINUTE, 59);
//将秒至59
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MONTH, month-1);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
}
return calendar.getTime().getTime();
}
/**
* 获取本月开始时间和结束时间时间戳
* @param index 0为开始时间 其他为结束时间
* @return
*/
public static Long getDayOfMonth(int index) {
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);
if (index == 0) {
//将小时至0
calendar.set(Calendar.HOUR_OF_DAY, 0);
//将分钟至0
calendar.set(Calendar.MINUTE, 0);
//将秒至0
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
} else {
//将小时至23
calendar.set(Calendar.HOUR_OF_DAY, 23);
//将分钟至59
calendar.set(Calendar.MINUTE, 59);
//将秒至59
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
}
return calendar.getTimeInMillis();
}
/**
* 将输入的时间转成Date类型
*
* @param inputDate 待转换时间
* @param patterns 带转换时间的可能格式 空则在默认格式中找
* @return 时间
*/
private static Date parseDate(String inputDate, String patterns) {
SimpleDateFormat df = new SimpleDateFormat();
final String[] localDateFormats = patterns != null ? new String[]{patterns} : DEFAULT_PATTERNS;
for (String pattern : localDateFormats) {
df.applyPattern(pattern);
//设置解析日期格式是否严格解析日期
df.setLenient(false);
ParsePosition pos = new ParsePosition(0);
Date date = df.parse(inputDate, pos);
if (pos.getIndex() == inputDate.length()) {
return date;
}
}
// 看看是否是微博的格式进行相关处理
//设置解析日期格式是否严格解析日期
sinaSDF.setLenient(false);
ParsePosition pos = new ParsePosition(0);
Date date = sinaSDF.parse(inputDate, pos);
if (pos.getIndex() == inputDate.length()) {
return date;
}
// 对于传入的时间戳进行兼容
if (StringUtils.isEmpty(patterns)) {
try {
return new Date(Long.valueOf(inputDate));
} catch (NumberFormatException e) {
}
}
String msg;
if (!StringUtils.isEmpty(patterns)) {
msg = String.format("%s的时间格式与传入的%s格式不匹配", inputDate, patterns);
} else {
msg = String.format("%s的时间格式与内置格式不匹配", inputDate);
}
throw new IllegalArgumentException(msg);
}
/**
* 对时间进行排序
*
* @param timeList 时间列表
* @param desc ture 倒序排列
*/
private static void sortTime(List<String> timeList, final boolean desc) {
Collections.sort(timeList, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return desc ? String.valueOf(o2).compareTo(String.valueOf(o1)) : -String.valueOf(o2).compareTo(String.valueOf(o1));
}
});
}
}