redisUtil工具类
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
DAteTimeUtil工具类
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.StringUtils;
public final class DateTimeUtil {
public final static String TIME_ZONE_CN = "GMT+8";
public final static String FMT_yyyyMMddHHmmssSa_12 = "yyyy-MM-dd KK:mm:ss.S a";
public final static String FMT_yyyyMMddHHmmssa_12 = "yyyy-MM-dd KK:mm:ss a";
public final static String FMT_yyyyMMddHHmma_12 = "yyyy-MM-dd KK:mm a";
public final static String FMT_yyyyMMddHHa_12 = "yyyy-MM-dd KK a";
public final static String FMT_yyyyMMddHHmmssSa = "yyyy-MM-dd HH:mm:ss.S a";
public final static String FMT_yyyyMMddHHmmssS = "yyyy-MM-dd HH:mm:ss.S";
public final static String FMT_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
public final static String FMT_yyyyMMddHHmm = "yyyy-MM-dd HH:mm";
public final static String FMT_yyyyMMddHH = "yyyy-MM-dd HH";
public final static String FMT_yyyyMMdda = "yyyy-MM-dd a";
public final static String FMT_yyyyMMdd = "yyyy-MM-dd";
public final static String FMT_yyyyMM = "yyyy-MM";
public final static String FMT_yyyyMMddHHmmssS_17 = "yyyyMMddHHmmssS";
public final static String FMT_yyyyMMddHHmmss_14 = "yyyyMMddHHmmss";
public final static String FMT_yyyyMMdd_8= "yyyyMMdd";
public final static String FMT_yyyyMM_6= "yyyyMM";
public final static String FMT_HHmmA_12 = "KK:mm a";
public final static String FMT_HHmmAz_12 = "KK:mm a,z";
public final static String FMT_HHmmAzzzz_12 = "KK:mm a,zzzz";
public final static String FMT_HHmmssA_12 = "KK:mm:ss a";
public final static String FMT_HHmmssAz_12 = "KK:mm:ss a,z";
public final static String FMT_HHmmssAzzzz_12 = "KK:mm:ss a,zzzz";
public final static String FMT_HHmmss = "HH:mm:ss";
public final static String FMT_HHmmssS = "HH:mm:ss.S";
public final static String FMT_HHmm = "HH:mm";
public final static String FMT_HHmmz = "HH:mm,z";
public final static String FMT_HHmmzzzz = "HH:mm,zzzz";
public final static String FMT_WWMMDDYY_EN = "EEE,MMM d,''yyyy";
public final static String FMT_WWMMDDYY_CN = "EEE,yyyy年MMMd号";
public final static String FMT_MMDDYY_EN = "MMM d,''yyyy";
public final static String FMT_MMDDYY_CN = "yyyy年MMMd号";
public final static String FMT_WW = "EEE";
private final static String[] formatStr = { FMT_yyyyMMddHHmmssS, FMT_yyyyMMddHHmmss, FMT_yyyyMMddHHmm,
FMT_yyyyMMddHH, FMT_yyyyMMdd, FMT_HHmmss, FMT_HHmmssS, FMT_HHmm, FMT_HHmmz, FMT_HHmmzzzz,
FMT_yyyyMMddHHmmssSa_12, FMT_yyyyMMddHHmmssa_12, FMT_yyyyMMddHHmma_12, FMT_yyyyMMddHHa_12,
FMT_yyyyMMdda, FMT_HHmmA_12, FMT_HHmmAz_12, FMT_HHmmAzzzz_12, FMT_HHmmssA_12, FMT_HHmmssAz_12,
FMT_HHmmssAzzzz_12, FMT_yyyyMMddHHmmssSa };
private DateTimeUtil() {
}
public static String formatDateTimetoString(Date date, String formatStr) {
String reStr = "";
if (date == null || formatStr == null || formatStr.trim().length() < 1) {
return reStr;
}
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(formatStr);
reStr = sdf.format(date);
return reStr == null ? "" : reStr;
}
public static Date getSystemDate(String fmtstr) {
try {
return parseToDate(formatDateTimetoString(getSystemDate(), fmtstr));
} catch (Exception e) {
e.printStackTrace();
return getSystemDate();
}
}
public static String formatDateTimetoString(Date date, String formatStr, Locale locale) {
String reStr = "";
if (date == null || formatStr == null || locale == null || formatStr.trim().length() < 1) {
return reStr;
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr, locale);
reStr = sdf.format(date);
return reStr == null ? "" : reStr;
}
public static String formatDateTimetoString(String dateStr, String formatStr) throws Exception {
String dStr = "";
if (dateStr != null && dateStr.trim().length() > 0 && formatStr != null && formatStr.trim().length() > 0) {
dStr = formatDateTimetoString(parseToDate(dateStr), formatStr);
}
return dStr;
}
public static String formatDateTimetoString(String dateStr, String formatStr, Locale locale) throws Exception {
String dStr = "";
if (dateStr != null && dateStr.trim().length() > 0 && formatStr != null && formatStr.trim().length() > 0
&& locale != null) {
dStr = formatDateTimetoString(parseToDate(dateStr, locale), formatStr, locale);
}
return dStr;
}
public static Date parseToDate(String dateTimeStr, String formatStr) throws Exception {
if (dateTimeStr == null || formatStr == null || dateTimeStr.trim().length() < 1
|| formatStr.trim().length() < 1) {
throw new IllegalArgumentException("参数dateTimeStr、formatStr不能是null或空格串!");
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
try {
return sdf.parse(dateTimeStr);
} catch (ParseException e) {
throw new Exception(e);
}
}
public static Date parseToDate(String dateTimeStr, String formatStr, Locale locale) throws Exception {
if (dateTimeStr != null && formatStr != null && locale != null && dateTimeStr.trim().length() > 0
&& formatStr.trim().length() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr, locale);
try {
return sdf.parse(dateTimeStr);
} catch (ParseException e) {
throw new Exception(e);
}
} else {
throw new IllegalArgumentException("参数dateTimeStr、formatStr、locale不能是null或空格串!");
}
}
public static Date parseToDate(String dateTimeStr) throws Exception {
if (dateTimeStr == null || dateTimeStr.trim().length() < 1) {
throw new IllegalArgumentException("参数dateTimeSt不能是null或空格串!");
}
int formatStrLength = formatStr.length;
int i = 0;
for (i = 0; i < formatStrLength; i++) {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr[i]);
try {
return sdf.parse(dateTimeStr);
} catch (ParseException e) {
}
}
throw new Exception("日期格式不正确!");
}
public static Date parseToDate(int year, int month, int day) throws Exception {
if (month < 1 || month > 12 || day < 1 || day > 31) {
throw new IllegalArgumentException("参数不正确!");
}
String yearStr = String.valueOf(year);
String monthStr = String.valueOf(month);
String dayStr = String.valueOf(day);
return parseToDate(yearStr + "-" + monthStr + "-" + dayStr);
}
public static Date parseToDate(int year, int month, int day, int h, int m, int s) throws Exception {
if (month < 1 || month > 12 || day < 1 || day > 31 || h < 0 || h > 23 || m < 0 || m > 60 || s < 0 || s > 60) {
throw new IllegalArgumentException("参数不正确!");
}
String yearStr = String.valueOf(year);
String monthStr = String.valueOf(month);
String dayStr = String.valueOf(day);
String hStr = String.valueOf(h);
String mStr = String.valueOf(m);
String sStr = String.valueOf(s);
return parseToDate(yearStr + "-" + monthStr + "-" + dayStr + " " + hStr + ":" + mStr + ":" + sStr);
}
public static Date parseToDate(String dateTimeStr, Locale locale) throws Exception {
if (dateTimeStr == null || dateTimeStr.trim().length() < 1 || locale == null) {
throw new IllegalArgumentException("参数dateTimeSt、locale不能是null或空格串!");
}
int formatStrLength = formatStr.length;
int i = 0;
SimpleDateFormat sdf = null;
for (i = 0; i < formatStrLength; i++) {
sdf = new SimpleDateFormat(formatStr[i], locale);
try {
return sdf.parse(dateTimeStr);
} catch (ParseException e) {
}
}
throw new Exception("日期格式不正确!");
}
public static String formatDateTimetoString(String dateTimeStr) throws Exception {
return formatDateTimetoString(dateTimeStr, FMT_yyyyMMddHHmmss);
}
public static String formatDateTimetoString(String dateTimeStr, Locale locale) throws Exception {
return formatDateTimetoString(dateTimeStr, FMT_yyyyMMddHHmmss, locale);
}
public static String formatDateTimetoString(Date dateTime) {
return formatDateTimetoString(dateTime, FMT_yyyyMMddHHmmss);
}
public static String formatDateTimetoString(Date dateTime, Locale locale) {
return formatDateTimetoString(dateTime, FMT_yyyyMMddHHmmss, locale);
}
public static String formatDatetoString(String dateStr) throws Exception {
return formatDateTimetoString(dateStr, FMT_yyyyMMdd);
}
public static String formatDatetoString(String dateStr, Locale locale) throws Exception {
return formatDateTimetoString(dateStr, FMT_yyyyMMdd, locale);
}
public static String formatDatetoString(Date d) {
return formatDateTimetoString(d, FMT_yyyyMMdd);
}
public static String formatDatetoString(Date d, Locale locale) {
return formatDateTimetoString(d, FMT_yyyyMMdd, locale);
}
public static String formatTimetoString(String dateTimeStr) throws Exception {
return formatDateTimetoString(dateTimeStr, FMT_HHmmss);
}
public static String formatTimetoString(String dateTimeStr, Locale locale) throws Exception {
return formatDateTimetoString(dateTimeStr, FMT_HHmmss, locale);
}
public static String formatTimetoString(Date dateTimeStr) {
return formatDateTimetoString(dateTimeStr, FMT_HHmmss);
}
public static String formatTimetoString(Date dateTimeStr, Locale locale) {
return formatDateTimetoString(dateTimeStr, FMT_HHmmss, locale);
}
public static int getYearOfDate(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
return calendar.get(Calendar.YEAR);
}
public static int getMonthOfYear(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
return calendar.get(Calendar.MONTH) + 1;
}
public static Date getDateByFirstDayOfMonth(Date d) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
public static int getDayOfMonth(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
return calendar.get(Calendar.DAY_OF_MONTH);
}
public static int getDayOfYear(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
return calendar.get(Calendar.DAY_OF_YEAR);
}
public static int getDayOfWeek(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
return calendar.get(Calendar.DAY_OF_WEEK) - 1;
}
public static int getWeekOfMonth(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
return calendar.get(Calendar.WEEK_OF_MONTH);
}
public static int getWeekOfYear(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public static int getHoursOfDay(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
return hours;
}
public static int getHoursOfDay12(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
int hours = calendar.get(Calendar.HOUR);
return hours;
}
public static int getMinutesOfHour(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
int minutes = calendar.get(Calendar.MINUTE);
return minutes;
}
public static int getSecondsOfMinute(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
int seconds = calendar.get(Calendar.SECOND);
return seconds;
}
public static int getMillisecondsOfSecond(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
int millisecond = calendar.get(Calendar.MILLISECOND);
return millisecond;
}
public static long getTime(Date d) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
return d.getTime();
}
public static int compareTwoDate(Date d1, Date d2) {
if (d1 == null || d2 == null) {
throw new IllegalArgumentException("参数d1或d2不能是null对象!");
}
long dI1 = d1.getTime();
long dI2 = d2.getTime();
if (dI1 > dI2) {
return -1;
} else if (dI1 < dI2) {
return 1;
} else {
return 0;
}
}
public static long getMillisecondsOfTwoDate(Date d1, Date d2) {
if (d1 == null || d2 == null) {
throw new IllegalArgumentException("参数d1或d2不能是null对象!");
}
long dI1 = d1.getTime();
long dI2 = d2.getTime();
return (dI1 - dI2);
}
public static double getSecondsOfTwoDate(Date d1, Date d2) {
if (d1 == null || d2 == null) {
throw new IllegalArgumentException("参数d1或d2不能是null对象!");
}
long i = getMillisecondsOfTwoDate(d1, d2);
return (double) i / 1000;
}
public static double getMinutesOfTwoDate(Date d1, Date d2) {
if (d1 == null || d2 == null) {
throw new IllegalArgumentException("参数d1或d2不能是null对象!");
}
long millions = getMillisecondsOfTwoDate(d1, d2);
return (double) millions / 60 / 1000;
}
public static double getHoursOfTwoDate(Date d1, Date d2) {
if (d1 == null || d2 == null) {
throw new IllegalArgumentException("参数d1或d2不能是null对象!");
}
long millions = getMillisecondsOfTwoDate(d1, d2);
return (double) millions / 60 / 60 / 1000;
}
public static double getDaysOfTwoDate(Date d1, Date d2) {
if (d1 == null || d2 == null) {
throw new IllegalArgumentException("参数d1或d2不能是null对象!");
}
long millions = getMillisecondsOfTwoDate(d1, d2);
return (double) millions / 24 / 60 / 60 / 1000;
}
public static Date addTime(Date d, double times, int type) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
long qv = 1;
switch (type) {
case Calendar.MILLISECOND:
qv = 1;
break;
case Calendar.SECOND:
qv = 1000;
break;
case Calendar.MINUTE:
qv = 1000 * 60;
break;
case Calendar.HOUR:
qv = 1000 * 60 * 60;
break;
case Calendar.DATE:
qv = 1000 * 60 * 60 * 24;
break;
default:
throw new RuntimeException("时间类型不正确!type=" + type);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
long milliseconds = (long) Math.round(Math.abs(times) * qv);
if (times > 0) {
for (; milliseconds > 0; milliseconds -= 2147483647) {
if (milliseconds > 2147483647) {
calendar.add(Calendar.MILLISECOND, 2147483647);
} else {
calendar.add(Calendar.MILLISECOND, (int) milliseconds);
}
}
} else {
for (; milliseconds > 0; milliseconds -= 2147483647) {
if (milliseconds > 2147483647) {
calendar.add(Calendar.MILLISECOND, -2147483647);
} else {
calendar.add(Calendar.MILLISECOND, -(int) milliseconds);
}
}
}
return calendar.getTime();
}
public static Date addYears(Date d, int years) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.YEAR, years);
return calendar.getTime();
}
public static Date addMonths(Date d, int months) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.MONTH, months);
return calendar.getTime();
}
public static Date addDays(Date d, int days) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.HOUR, days * 24);
return calendar.getTime();
}
public static Date addHours(Date d, int hours) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.HOUR, hours);
return calendar.getTime();
}
public static Date addMinutes(Date d, int minutes) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.MINUTE, minutes);
return calendar.getTime();
}
public static Date addSeconds(Date d, int seconds) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.SECOND, seconds);
return calendar.getTime();
}
public static Date addMilliseconds(Date d, int milliseconds) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.MILLISECOND, milliseconds);
return calendar.getTime();
}
public static Date setYearOfDate(Date d, int year) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.YEAR, year);
return calendar.getTime();
}
public static Date setMonthOfDate(Date d, int month) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.MONTH, month);
return calendar.getTime();
}
public static Date setDayOfDate(Date d, int day) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.DAY_OF_MONTH, day);
return calendar.getTime();
}
public static Date setHourOfDate(Date d, int hour) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.HOUR_OF_DAY, hour);
return calendar.getTime();
}
public static Date setMinuteOfDate(Date d, int minute) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.MINUTE, minute);
return calendar.getTime();
}
public static Date setSecondOfDate(Date d, int second) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.SECOND, second);
return calendar.getTime();
}
public static Date setMillisecondOfDate(Date d, int millisecond) {
if (d == null) {
throw new IllegalArgumentException("参数d不能是null对象!");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.MILLISECOND, millisecond);
return calendar.getTime();
}
public static int getDaysOfMonth(Date d) {
int year = getYearOfDate(d);
int month = getMonthOfYear(d);
return getDaysOfMonth(year, month);
}
public static int getDaysOfMonth(int year, int month) {
int days = 0;
if (month == 2) {
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
days = 29;
} else {
days = 28;
}
}
if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
days = 30;
}
if ((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10)
|| (month == 12)) {
days = 31;
}
return days;
}
public static Date getSystemDate() {
return new Date(System.currentTimeMillis());
}
public static long getSystemTime() {
return System.currentTimeMillis();
}
public static Date getLastDay(Date date) {
long day = date.getTime();
long lastDay = day - 24 * 60 * 60 * 1000;
return new Date(lastDay);
}
public static Date getTomorrow(Date date) {
long day = date.getTime();
long tomorrow = day + 24 * 60 * 60 * 1000;
return new Date(tomorrow);
}
public static Date getDayLastMonth() {
long day = new Date().getTime();
long dayLastMonth = day - 24 * 60 * 60 * 1000 * 20;
return new Date(dayLastMonth);
}
public static Date getDayNextMonth() {
long day = new Date().getTime();
long dayNextMonth = day + 20 * 24 * 60 * 60 * 1000;
return new Date(dayNextMonth);
}
public static int getMonthCount(Date sDate, Date eDate) {
String sDateStr = DateTimeUtil.formatDateTimetoString(sDate, "MM");
String eDateStr = DateTimeUtil.formatDateTimetoString(eDate, "MM");
int monthCount = Integer.parseInt(eDateStr) - Integer.parseInt(sDateStr) + 1;
return monthCount;
}
public static int getYearCount(Date sDate, Date eDate) {
String sDateStr = DateTimeUtil.formatDateTimetoString(sDate, "yyyy");
String eDateStr = DateTimeUtil.formatDateTimetoString(eDate, "yyyy");
return Integer.parseInt(eDateStr) - Integer.parseInt(sDateStr);
}
public static Date getDayNextMonth(Date date) {
String yearStr = DateTimeUtil.formatDateTimetoString(date, "yyyy");
String monthStr = DateTimeUtil.formatDateTimetoString(date, "MM");
String dayStr = DateTimeUtil.formatDateTimetoString(date, "dd");
int year = Integer.parseInt(yearStr);
int month = Integer.parseInt(monthStr);
if (month == 12) {
month = 1;
year = year + 1;
yearStr = String.valueOf(year);
monthStr = String.valueOf(month);
}
String dateStr = yearStr + "-" + monthStr + "-" + dayStr;
try {
date = DateTimeUtil.parseToDate(dateStr);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
public static Date getCurrentMouthStart() {
Date d = getSystemDate();
d = setDayOfDate(d, 1);
d = setHourOfDate(d, 0);
d = setMinuteOfDate(d, 0);
d = setSecondOfDate(d, 0);
return d;
}
public static Date getDateNextMonth(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, +1);
return cal.getTime();
}
public static Integer daysDifference(Date date) {
long l1 = get24HourMill(date);
long l2 = get24HourMill(new Date());
return (int) ((l2 - l1) / 86400 / 1000);
}
private static long get24HourMill(Date d) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
public static Date getZeroDate(Date d) {
if (d == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
public static Date getLastDate(Date date) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
private static String otherDiff(Date startDate, Date endDate) {
String[] type = new String[] { "年", "个月", "星期", "天", "小时", "分钟", "秒", "秒" };
Object[] obj = timeDifference(startDate, endDate);
String value = "1秒前";
for (int i = 0; i < obj.length; i++) {
if (!"0".equals(obj[i].toString())) {
value = obj[i].toString() + type[i] + "前";
break;
}
}
return value;
}
public static String dynDiff(Date startDate, Date endDate) {
String startDay = DateFormatUtils.format(startDate, "dd");
String endtDay = DateFormatUtils.format(endDate, "dd");
String value = "";
if (startDay.equals(endtDay)) {
value = DateFormatUtils.format(startDate, " HH:mm");
} else {
value = otherDiff(startDate, endDate);
}
return value;
}
public static String resDiff(Date startDate, Date endDate) {
Object[] obj = timeDifference(startDate, endDate);
String value = "";
if (Long.parseLong(obj[3].toString()) > 7) {
value = DateFormatUtils.format(startDate, "yyyy-MM-dd HH:mm");
} else {
value = otherDiff(startDate, endDate);
}
return value;
}
private static Object[] timeDifference(Date startTime, Date endTime) {
if (startTime == null || endTime == null) {
return new Object[] { 0, 0, 0, 0, 0, 0, 0 };
} else {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.setTime(startTime);
end.setTime(endTime);
long startMs = start.getTimeInMillis();
long endMs = end.getTimeInMillis();
long l_differ = endMs - startMs;
long ll_differ = l_differ / 1000;
long second_differ = l_differ / 1000;
long year_differ = second_differ / (60 * 60 * 24 * 365);
long month_differ = second_differ / (60 * 60 * 24 * 30);
long week_differ = second_differ / (60 * 60 * 24 * 7);
long day_differ = second_differ / (60 * 60 * 24);
second_differ = second_differ - day_differ * 60 * 60 * 24;
long hour_differ = second_differ / (60 * 60);
second_differ = second_differ - hour_differ * 60 * 60;
long minute_differ = second_differ / 60;
second_differ = second_differ - minute_differ * 60;
return new Object[] { year_differ, month_differ, week_differ, day_differ, hour_differ, minute_differ,
second_differ, ll_differ };
}
}
public static String getPastDate(Date date) throws Exception {
String timeStr;
Date currDate = getSystemDate();
if (date.before(getZeroDate(currDate))) {
timeStr = DateTimeUtil.formatDatetoString(date);
} else {
double hours = DateTimeUtil.getHoursOfTwoDate(currDate, date);
if (hours < 24 && hours >= 1) {
timeStr = String.valueOf((int) hours) + "小时前";
} else {
double minutes = DateTimeUtil.getMinutesOfTwoDate(currDate, date);
if (minutes < 60 && minutes >= 1) {
timeStr = String.valueOf((int) minutes) + "分钟前";
} else {
double seconds = DateTimeUtil.getSecondsOfTwoDate(currDate, date);
if (seconds < 60 && seconds >= 1) {
timeStr = "刚刚";
} else {
timeStr = "-";
}
}
}
}
return timeStr;
}
public static String getFormatDate(Date date, String format) {
if(date == null) {
return "";
} else {
SimpleDateFormat sdf = null;
boolean hasLength = StringUtils.hasLength(format);
if(hasLength) {
try {
sdf = new SimpleDateFormat(format);
return sdf.format(date);
} catch (Exception arg6) {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return sdf.format(date);
} catch (Exception arg5) {
;
}
}
} else {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return sdf.format(date);
} catch (Exception arg7) {
;
}
}
return "";
}
}
}
JsonUtils工具类
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class JsonUtils {
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
MD5Utils工具类
import org.apache.commons.codec.binary.Base64;
import java.security.MessageDigest;
public class MD5Utils {
public static String getMD5Str(String strValue) throws Exception {
MessageDigest md5 = MessageDigest.getInstance("MD5");
String newstr = Base64.encodeBase64String(md5.digest(strValue.getBytes()));
return newstr;
}
}
CookieUtils工具类
```java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
*
* @Title: CookieUtils.java
* @Description: Cookie 工具类
*/
public final class CookieUtils {
final static Logger logger = LoggerFactory.getLogger(CookieUtils.class);
/**
*
* @Description: 得到Cookie的值, 不编码
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, false);
}
/**
*
* @Description: 得到Cookie的值
* @param request
* @param cookieName
* @param isDecoder
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}
/**
*
* @Description: 得到Cookie的值
* @param request
* @param cookieName
* @param encodeString
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}
/**
*
* @Description: 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
* @param request
* @param response
* @param cookieName
* @param cookieValue
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue) {
setCookie(request, response, cookieName, cookieValue, -1);
}
/**
*
* @Description: 设置Cookie的值 在指定时间内生效,但不编码
* @param request
* @param response
* @param cookieName
* @param cookieValue
* @param cookieMaxage
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage) {
setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
}
/**
*
* @Description: 设置Cookie的值 不设置生效时间,但编码
* 在服务器被创建,返回给客户端,并且保存客户端
* 如果设置了SETMAXAGE(int seconds),会把cookie保存在客户端的硬盘中
* 如果没有设置,会默认把cookie保存在浏览器的内存中
* 一旦设置setPath():只能通过设置的路径才能获取到当前的cookie信息
* @param request
* @param response
* @param cookieName
* @param cookieValue
* @param isEncode
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, boolean isEncode) {
setCookie(request, response, cookieName, cookieValue, -1, isEncode);
}
/**
*
* @Description: 设置Cookie的值 在指定时间内生效, 编码参数
* @param request
* @param response
* @param cookieName
* @param cookieValue
* @param cookieMaxage
* @param isEncode
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage, boolean isEncode) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
}
/**
*
* @Description: 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
* @param request
* @param response
* @param cookieName
* @param cookieValue
* @param cookieMaxage
* @param encodeString
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
String cookieValue, int cookieMaxage, String encodeString) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
}
/**
*
* @Description: 删除Cookie带cookie域名
* @param request
* @param response
* @param cookieName
*/
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName) {
doSetCookie(request, response, cookieName, null, -1, false);
// doSetCookie(request, response, cookieName, "", -1, false);
}
/**
*
* @Description: 设置Cookie的值,并使其在指定时间内生效
* @param request
* @param response
* @param cookieName
* @param cookieValue
* @param cookieMaxage cookie生效的最大秒数
* @param isEncode
*/
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
try {
if (cookieValue == null) {
cookieValue = "";
} else if (isEncode) {
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0)
cookie.setMaxAge(cookieMaxage);
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
logger.info("========== domainName: {} ==========", domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @Description: 设置Cookie的值,并使其在指定时间内生效
* @param request
* @param response
* @param cookieName
* @param cookieValue
* @param cookieMaxage cookie生效的最大秒数
* @param encodeString
*/
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
try {
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0)
cookie.setMaxAge(cookieMaxage);
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
logger.info("========== domainName: {} ==========", domainName);
if (!"localhost".equals(domainName)) {
cookie.setDomain(domainName);
}
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @Description: 得到cookie的域名
* @return
*/
private static final String getDomainName(HttpServletRequest request) {
String domainName = null;
String serverName = request.getRequestURL().toString();
if (serverName == null || serverName.equals("")) {
domainName = "";
} else {
serverName = serverName.toLowerCase();
serverName = serverName.substring(7);
final int end = serverName.indexOf("/");
serverName = serverName.substring(0, end);
if (serverName.indexOf(":") > 0) {
String[] ary = serverName.split("\\:");
serverName = ary[0];
}
final String[] domains = serverName.split("\\.");
int len = domains.length;
if (len > 3 && !isIp(serverName)) {
// www.xxx.com.cn
domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
} else if (len <= 3 && len > 1) {
// xxx.com or xxx.cn
domainName = "." + domains[len - 2] + "." + domains[len - 1];
} else {
domainName = serverName;
}
}
return domainName;
}
public static String trimSpaces(String IP){//去掉IP字符串前后所有的空格
while(IP.startsWith(" ")){
IP= IP.substring(1,IP.length()).trim();
}
while(IP.endsWith(" ")){
IP= IP.substring(0,IP.length()-1).trim();
}
return IP;
}
public static boolean isIp(String IP){//判断是否是一个IP
boolean b = false;
IP = trimSpaces(IP);
if(IP.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")){
String s[] = IP.split("\\.");
if(Integer.parseInt(s[0])<255)
if(Integer.parseInt(s[1])<255)
if(Integer.parseInt(s[2])<255)
if(Integer.parseInt(s[3])<255)
b = true;
}
return b;
}
}