package project.web.api;
|
|
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.logging.Log;
|
import org.apache.commons.logging.LogFactory;
|
|
import javax.servlet.http.HttpServletRequest;
|
import java.net.URLDecoder;
|
import java.sql.Timestamp;
|
import java.text.*;
|
import java.time.Instant;
|
import java.time.LocalDate;
|
import java.time.LocalDateTime;
|
import java.time.ZoneId;
|
import java.time.format.DateTimeFormatter;
|
import java.util.*;
|
|
|
/**
|
* SafeUtils
|
*
|
* @author zhuf
|
* @date 2014-12-16
|
*/
|
public class SafeUtils {
|
private static Log log = LogFactory.getLog(SafeUtils.class.getName());
|
public static final String DATE_FORMAT = "yyyy-MM-dd";
|
public static final String DATE_FORMAT1 = "yyyyMMdd";
|
public static final String DATE_FORMAT2 = "yyyy年MM月dd日";
|
public static final String TIME_FORMAT = "HH:mm:ss";
|
public static final String DATE_TIME_FORMAT1 = "yyyy-MM-dd HH:mm:ss";
|
public static final String DATE_TIME_FORMAT2 = "yyyyMMddHHmmss";
|
|
public static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.S";
|
|
public static final String BOOKKEEPDATE_INX = "9999000";
|
|
private static Calendar ca = Calendar.getInstance();
|
|
public static String JSON = "JSON";
|
public static String TEXT = "TEXT";
|
|
public static String generateGUID() {
|
UUID tmpuuid = UUID.randomUUID();
|
String tmpstr = tmpuuid.toString();
|
tmpstr = tmpstr.replaceAll("-", "");
|
return tmpstr;
|
}
|
|
/**
|
* 根据时间加随机数生成订单号
|
*/
|
public static String createOrderNum(Integer num){
|
return SafeUtils.convertDateToString(new Date(),SafeUtils.DATE_TIME_FORMAT2)+SafeUtils.getRandomStr(num);
|
}
|
|
/**
|
* 地球半径,单位 km
|
*/
|
private static final double EARTH_RADIUS = 6378.137;
|
|
/**
|
* 根据经纬度,计算两点间的距离
|
*
|
* @param longitude1 第一个点的经度
|
* @param latitude1 第一个点的纬度
|
* @param longitude2 第二个点的经度
|
* @param latitude2 第二个点的纬度
|
* @return 返回距离 单位千米
|
*/
|
public static String getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
|
// 纬度
|
double lat1 = Math.toRadians(latitude1);
|
double lat2 = Math.toRadians(latitude2);
|
// 经度
|
double lng1 = Math.toRadians(longitude1);
|
double lng2 = Math.toRadians(longitude2);
|
// 纬度之差
|
double a = lat1 - lat2;
|
// 经度之差
|
double b = lng1 - lng2;
|
// 计算两点距离的公式
|
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
|
Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(b / 2), 2)));
|
// 弧长乘地球半径, 返回单位: 千米
|
s = s * EARTH_RADIUS;
|
return String.valueOf(s);
|
}
|
|
/**
|
* 获取现在时间
|
*
|
* @return 返回时间类型 yyyy-MM-dd HH:mm:ss
|
*/
|
public static Date getNowDate() {
|
Date currentTime = new Date();
|
return currentTime;
|
}
|
|
/*public static Date addMonth(Date date,int month){
|
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
|
String str="20110823";
|
Date dt=sdf.parse(str);
|
Calendar rightNow = Calendar.getInstance();
|
rightNow.setTime(dt);
|
rightNow.add(Calendar.YEAR,-1);//日期减1年
|
rightNow.add(Calendar.MONTH,3);//日期加3个月
|
rightNow.add(Calendar.DAY_OF_YEAR,10);//日期加10天
|
Date dt1=rightNow.getTime();
|
String reStr = sdf.format(dt1);
|
System.out.println(reStr);
|
}*/
|
|
/**
|
* 判断日期是否是当天日期
|
*
|
* @return Boolean
|
*/
|
public static Boolean isDangri(Date date) {
|
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
|
if (s.format(date).toString().equals(s.format(new Date()).toString())) {
|
return true;
|
}else {
|
return false;
|
}
|
}
|
|
/**
|
* 获取30天前的日期
|
*
|
* @return Boolean
|
*/
|
public static String thirtyDays(){
|
|
//时间格式定义
|
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
//获取当前时间日期--nowDate
|
String nowDate = format.format(new Date());
|
//获取30天前的时间日期
|
Calendar calc = Calendar.getInstance();
|
calc.add(Calendar.DAY_OF_MONTH, -30);
|
return format.format(calc.getTime());
|
}
|
|
/**
|
* 判断日期是否在30天之内
|
*
|
* @return Boolean
|
*/
|
public static Boolean isDangyue(Date date){
|
|
boolean convertSuccess=true;
|
//时间格式定义
|
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
//获取当前时间日期--nowDate
|
String nowDate = format.format(new Date());
|
//获取30天前的时间日期--minDate
|
Calendar calc = Calendar.getInstance();
|
calc.add(Calendar.DAY_OF_MONTH, -30);
|
String minDate = format.format(calc.getTime());
|
format.setLenient(false);
|
//获取字符串转换后的时间--strDate
|
String strDate = format.format(date);
|
convertSuccess = nowDate.compareTo(strDate) >= 0 && strDate.compareTo(minDate) >= 0;
|
return convertSuccess;
|
}
|
|
/**
|
* 两个日期的时间差 --- 小时
|
*
|
* @return String
|
*/
|
public static long getDatePoorHour(Date endDate) {
|
long nd = 1000 * 24 * 60 * 60;
|
long nh = 1000 * 60 * 60;
|
long nm = 1000 * 60;
|
// long ns = 1000;
|
// 获得两个时间的毫秒时间差异
|
long diff = new Date().getTime() - endDate.getTime();
|
// 计算差多少天
|
long day = diff / nd;
|
// 计算差多少小时
|
long hour = diff % nd / nh;
|
// 计算差多少分钟
|
long min = diff % nd % nh / nm;
|
// 计算差多少秒//输出结果
|
// long sec = diff % nd % nh % nm / ns;
|
return hour;
|
}
|
|
/**
|
* 两个日期的时间差 --- 小时
|
*
|
* @return String
|
*/
|
public static long getDatePoorMin(Date endDate) {
|
long nd = 1000 * 24 * 60 * 60;
|
long nh = 1000 * 60 * 60;
|
long nm = 1000 * 60;
|
// long ns = 1000;
|
// 获得两个时间的毫秒时间差异
|
long diff = new Date().getTime() - endDate.getTime();
|
// 计算差多少天
|
long day = diff / nd;
|
// 计算差多少小时
|
long hour = diff % nd / nh;
|
// 计算差多少分钟
|
long min = diff % nd % nh / nm;
|
// 计算差多少秒//输出结果
|
// long sec = diff % nd % nh % nm / ns;
|
return min;
|
}
|
|
/**
|
* 两个日期(Date)的时间差---天数(long)
|
*
|
* @return long
|
*/
|
public static long getDayNum(Date date1, Date date2){
|
Long time1 = date1.getTime();
|
Long time2 = date2.getTime();
|
Long time;
|
if(time2>time1){
|
time=time2-time1;
|
}else{
|
time=time1-time2;
|
}
|
long days = time / (1000 * 60 * 60 * 24);
|
return days;
|
}
|
|
/**
|
* 根据date返回String的时间 精确到日
|
*
|
* @return Boolean
|
*/
|
public static String jingQueDay(Date date){
|
SimpleDateFormat s = new SimpleDateFormat("MM-dd",Locale.SIMPLIFIED_CHINESE);
|
return s.format(date).toString();
|
}
|
|
/**
|
* 根据date返回String的时间 精确到年
|
*
|
* @return Boolean
|
*/
|
public static String jingQueYear(Date date){
|
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
|
return s.format(date).toString();
|
}
|
|
public static int getInt(Object obj) {
|
int tmpret = 0;
|
if (obj != null) {
|
try {
|
tmpret = Integer.parseInt(obj.toString());
|
} catch (Exception ex) {
|
|
}
|
}
|
return tmpret;
|
}
|
|
public static Long getLong(Object obj, Long defvalue) {
|
Long tmpret = defvalue;
|
if (obj != null) {
|
try {
|
tmpret = Long.parseLong(obj.toString());
|
} catch (Exception ex) {
|
}
|
}
|
return tmpret;
|
}
|
|
public static Long getLong(Object obj) {
|
Long tmpret = 0L;
|
if (obj != null) {
|
try {
|
if (!obj.toString().equals(""))
|
tmpret = Long.parseLong(obj.toString());
|
} catch (Exception ex) {
|
}
|
}
|
return tmpret;
|
}
|
|
public static int getInt(Object obj, int defvalue) {
|
int tmpret = defvalue;
|
if (obj != null) {
|
try {
|
if (!obj.toString().equals(""))
|
tmpret = Integer.parseInt(obj.toString());
|
} catch (Exception ex) {
|
|
}
|
}
|
return tmpret;
|
}
|
|
public static Integer getInteger(Object obj) {
|
Integer tmpret = new Integer(0);
|
if (obj != null) {
|
try {
|
tmpret = Integer.valueOf(obj.toString());
|
} catch (Exception ex) {
|
log.error("getInteger:" + ex);
|
}
|
}
|
return tmpret;
|
}
|
|
public static Integer getInteger(Object obj, int defvalue) {
|
Integer tmpret = new Integer(defvalue);
|
if (obj != null) {
|
try {
|
tmpret = Integer.valueOf(obj.toString());
|
} catch (Exception ex) {
|
log.error("getInteger:" + ex);
|
}
|
}
|
return tmpret;
|
}
|
|
public static double getDouble(Object obj) {
|
double tmpvalue = 0;
|
try {
|
if(null != obj)
|
tmpvalue = Double.parseDouble(obj.toString());
|
} catch (Exception ex) {
|
}
|
return tmpvalue;
|
}
|
|
public static double getDouble(Object obj, double defvalue) {
|
double tmpvalue = defvalue;
|
try {
|
tmpvalue = Double.parseDouble(obj.toString());
|
} catch (Exception ex) {
|
log.error("getDouble :" + ex);
|
}
|
return tmpvalue;
|
}
|
|
public static String getString(Object obj) {
|
String tmpret = "";
|
if (obj != null)
|
tmpret = obj.toString();
|
return tmpret.trim();
|
}
|
|
public static String getStringWithUrlEncode(Object obj) {
|
String tmpret = "";
|
if (obj != null) {
|
try {
|
tmpret = URLDecoder.decode(obj.toString(), "utf-8");
|
} catch (Exception ex) {
|
log.error("getStringWithUrlEncode:" + ex);
|
}
|
}
|
return tmpret.trim();
|
}
|
|
public static java.sql.Date getSqlDate(Object obj) {
|
java.sql.Date tmpdate = null;
|
if (obj != null) {
|
try {
|
tmpdate = java.sql.Date.valueOf(obj.toString());
|
} catch (Exception ex) {
|
log.error("getDate :" + ex);
|
}
|
}
|
return tmpdate;
|
}
|
|
public static java.sql.Date getSqlDate(String obj) {
|
java.sql.Date tmpdate = null;
|
if (obj != null) {
|
try {
|
tmpdate = java.sql.Date.valueOf(obj.toString());
|
} catch (Exception ex) {
|
log.error("getDate :" + ex);
|
}
|
}
|
return tmpdate;
|
}
|
|
/**
|
* 获取当前时间
|
*
|
* @return
|
*/
|
public static int getCurrentUnixTime() {
|
int tmpCurrentTime = (int) (System.currentTimeMillis() / 1000);
|
return tmpCurrentTime;
|
}
|
|
public static Date getUTCDate(long times) {
|
|
// 1、取得本地时间:
|
Calendar cal = Calendar.getInstance();
|
cal.setTimeInMillis(times * 1000);
|
|
// 2、取得时间偏移量:
|
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
|
|
// 3、取得夏令时差:
|
int dstOffset = cal.get(Calendar.DST_OFFSET);
|
|
// 4、从本地时间里扣除这些差量,即可以取得UTC时间:
|
cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
|
|
// 之后调用cal.get(int x)或cal.getTimeInMillis()方法所取得的时间即是UTC标准时间。
|
return new Date(cal.getTimeInMillis());
|
}
|
|
/**
|
* long 转换为 datestr
|
*
|
* @param dateTimes
|
* @param format
|
* @return
|
*/
|
public static String convertLongToString(long dateTimes, String format) {
|
if (dateTimes == 0)
|
return "";
|
else {
|
ca.setTimeInMillis(dateTimes);
|
SimpleDateFormat s = new SimpleDateFormat(format);
|
String dateString = s.format(ca.getTime());
|
return dateString;
|
}
|
}
|
|
/*
|
* 获取时间偏移量
|
*/
|
public static final String getDayStrByOffset(int dayoffset) {
|
Calendar tmpcalendar = Calendar.getInstance();
|
tmpcalendar.add(Calendar.DAY_OF_YEAR, dayoffset);
|
Date tmpdate = tmpcalendar.getTime();
|
return getFormatDate(tmpdate, "yyyyMMdd");
|
}
|
|
public static final String getFormatDate(Date date, String format) {
|
String tmpstr = "";
|
if (format == null)
|
format = "yyyy-MM-dd HH:mm:ss";
|
DateFormat format1 = new SimpleDateFormat(format);
|
tmpstr = format1.format(date);
|
return tmpstr;
|
}
|
|
|
/**
|
* 1代表1周,2->2周,3->3周,4->一个月
|
* @return
|
*/
|
public static final int getOffsetByDate(int begindate,int enddate){
|
int dateoff = 0;
|
int offset = enddate - begindate;
|
switch(offset){
|
case 7:
|
dateoff = 1;
|
break;
|
case 14:
|
dateoff = 2;
|
break;
|
case 21:
|
dateoff = 3;
|
break;
|
case 30:
|
dateoff = 4;
|
break;
|
}
|
return dateoff;
|
}
|
|
/**
|
* sqltimestamp int 转换为 datestr
|
*
|
* @param dateTimes
|
* @param format
|
* @return
|
*/
|
public static String convertIntegerToString(long dateTimes, String format) {
|
if (dateTimes == 0)
|
return "";
|
else {
|
ca.setTimeInMillis(dateTimes * 1000);
|
SimpleDateFormat s = new SimpleDateFormat(format);
|
String dateString = s.format(ca.getTime());
|
return dateString;
|
}
|
}
|
|
/**
|
* 将日期格式的字符串转换为长整型
|
*
|
* @param date
|
* @param format
|
* @return
|
*/
|
public static long convert2long(String date, String format) {
|
try {
|
if (StringUtils.isNotBlank(date)) {
|
if (StringUtils.isBlank(format))
|
format = "yyyy-MM-dd HH:mm:ss";
|
|
SimpleDateFormat sf = new SimpleDateFormat(format);
|
return sf.parse(date).getTime();
|
}
|
} catch (ParseException e) {
|
e.printStackTrace();
|
}
|
return 0l;
|
}
|
|
/**
|
* date 转为 string
|
*
|
* @param date
|
* @param format
|
* @return
|
*/
|
public static String convertDateToString(Date date, String format) {
|
SimpleDateFormat s = new SimpleDateFormat(format);
|
String dateString = s.format(date);
|
return dateString;
|
}
|
|
/**
|
* date str 转为 long
|
*
|
* @param date
|
* @param format
|
* @return
|
* @throws ParseException
|
*/
|
public static long convertStringToLong(String date, String format)
|
throws ParseException {
|
try {
|
SimpleDateFormat s = new SimpleDateFormat(format);
|
ca.setTime(s.parse(date));
|
return ca.getTimeInMillis() / 1000;
|
} catch (Exception e) {
|
return 0;
|
}
|
|
}
|
|
/**
|
* date str 转为 Date
|
*
|
* @param date
|
* @param format
|
* @return
|
* @throws ParseException
|
*/
|
public static Date convertStringToDate(String date, String format)
|
throws ParseException {
|
try {
|
SimpleDateFormat s = new SimpleDateFormat(format);
|
ca.setTime(s.parse(date));
|
return convertLongToDate(ca.getTimeInMillis() / 1000);
|
} catch (Exception e) {
|
log.error("SafeUtils.convertStringToDate error",e);
|
return new Date();
|
}
|
|
}
|
|
/**
|
* long 转换为 date
|
*
|
* @param dateTimes
|
* @return
|
*/
|
public static Date convertLongToDate(long dateTimes) {
|
if (dateTimes == 0)
|
return new Date();
|
else {
|
ca.setTimeInMillis(Long.parseLong(dateTimes + "000"));
|
return ca.getTime();
|
}
|
}
|
|
/**
|
* String 转换为 localdate
|
* @param date
|
* @return
|
*/
|
public static LocalDate convertStringToLoaclDate(String date){
|
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
return LocalDate.parse(date, fmt);
|
}
|
|
/**
|
* date 转换为 localdate
|
* @param date
|
*/
|
public static LocalDate convertDateToLocalDate(Date date) {
|
Instant instant = date.toInstant();
|
ZoneId zone = ZoneId.systemDefault();
|
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
|
LocalDate localDate = localDateTime.toLocalDate();
|
return localDate;
|
}
|
|
/**
|
* localdate转 date
|
*/
|
public static Date convertLocalDateToDate(LocalDate date) {
|
if (date != null) {
|
ZoneId zone = ZoneId.systemDefault();
|
Instant instant = date.atStartOfDay().atZone(zone).toInstant();
|
return Date.from(instant);
|
} else {
|
return null;
|
}
|
|
}
|
|
|
|
/**
|
* 得到某年某周的第一天
|
*
|
* @param year
|
* @param week
|
* @return
|
*/
|
public static Date getFirstDayOfWeek(int year, int week) {
|
week = week - 1;
|
Calendar calendar = Calendar.getInstance();
|
calendar.set(Calendar.YEAR, year);
|
calendar.set(Calendar.MONTH, Calendar.JANUARY);
|
calendar.set(Calendar.DATE, 1);
|
|
Calendar cal = (Calendar) calendar.clone();
|
cal.add(Calendar.DATE, week * 7);
|
|
return getFirstDayOfWeek(cal.getTime());
|
}
|
|
/**
|
* 得到某年某周的最后一天
|
*
|
* @param year
|
* @param week
|
* @return
|
*/
|
public static Date getLastDayOfWeek(int year, int week) {
|
week = week - 1;
|
Calendar calendar = Calendar.getInstance();
|
calendar.set(Calendar.YEAR, year);
|
calendar.set(Calendar.MONTH, Calendar.JANUARY);
|
calendar.set(Calendar.DATE, 1);
|
Calendar cal = (Calendar) calendar.clone();
|
cal.add(Calendar.DATE, week * 7);
|
|
return getLastDayOfWeek(cal.getTime());
|
}
|
|
/**
|
* 取得当前日期所在周的第一天
|
*
|
* @param date
|
* @return
|
*/
|
public static Date getFirstDayOfWeek(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
|
calendar.setTime(date);
|
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // Sunday
|
return calendar.getTime();
|
}
|
|
/**
|
* 取得当前日期所在周的最后一天
|
*
|
* @param date
|
* @return
|
*/
|
public static Date getLastDayOfWeek(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setFirstDayOfWeek(Calendar.MONDAY);
|
calendar.setTime(date);
|
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek() + 6); // Sunday
|
return calendar.getTime();
|
}
|
//获取该日期上周的周一 @author:H-T-C
|
public static Date geLastWeekMonday(Date date) {
|
Calendar cal = Calendar.getInstance();
|
cal.setTime(getThisWeekMonday(date));
|
cal.add(Calendar.DATE, -7);
|
return cal.getTime();
|
}
|
//获取该日期上周的周日 @author:H-T-C
|
public static Date geLastWeekSunday(Date date) {
|
Calendar cal = Calendar.getInstance();
|
cal.setTime(getThisWeekMonday(date));
|
cal.add(Calendar.DATE, -1);
|
return cal.getTime();
|
}
|
//获取该日期本周的周一 @author:H-T-C
|
public static Date getThisWeekMonday(Date date) {
|
Calendar cal = Calendar.getInstance();
|
cal.setTime(date);
|
// 获得当前日期是一个星期的第几天
|
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
|
if (1 == dayWeek) {
|
cal.add(Calendar.DAY_OF_MONTH, -1);
|
}
|
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
|
cal.setFirstDayOfWeek(Calendar.MONDAY);
|
// 获得当前日期是一个星期的第几天
|
int day = cal.get(Calendar.DAY_OF_WEEK);
|
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
|
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
|
return cal.getTime();
|
}
|
/**
|
* 取得当前日期所在周第几天
|
* @param date
|
* @return
|
*/
|
public static int getDayOfWeek(LocalDate date){
|
Calendar cal=Calendar.getInstance();
|
cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
|
cal.setTime(convertLocalDateToDate(date));
|
int w=cal.get(Calendar.DAY_OF_WEEK);
|
if(w<0){
|
w=0;
|
}
|
return w;
|
}
|
|
|
/**
|
* 取得当前日期与当前日期所在周最后一天相差秒数
|
* @return
|
*/
|
public static long getDateDiff() {
|
Date now = new Date();
|
Date lastDay = getLastDayOfLastWeek(now);
|
long seconds = now.getTime() - lastDay.getTime();
|
return seconds;
|
}
|
|
public static long daysDiff(Date bigDay, Date smallDay) {
|
long t = (bigDay.getTime() - smallDay.getTime()) / (3600 * 24 * 1000);
|
return t;
|
}
|
|
//获取昨日日期yyyy-MM-dd @author:H-T-C
|
public static String getYesterday(){
|
Calendar cal = Calendar.getInstance();
|
cal.add(Calendar.DATE, -1);
|
return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
|
}
|
|
/**
|
* 取得当前日期所在周的前一周最后一天
|
*
|
* @param date
|
* @return
|
*/
|
public static Date getLastDayOfLastWeek(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
return getLastDayOfWeek(calendar.get(Calendar.YEAR),
|
calendar.get(Calendar.WEEK_OF_YEAR) - 1);
|
}
|
|
/**
|
* 返回指定日期的月的第一天
|
*
|
* @return
|
*/
|
public static Date getFirstDayOfMonth(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
|
1);
|
return calendar.getTime();
|
}
|
|
/**
|
* 返回指定年月的月的第一天
|
*
|
* @param year
|
* @param month
|
* @return
|
*/
|
public static Date getFirstDayOfMonth(Integer year, Integer month) {
|
Calendar calendar = Calendar.getInstance();
|
if (year == null) {
|
year = calendar.get(Calendar.YEAR);
|
}
|
if (month == null) {
|
month = calendar.get(Calendar.MONTH);
|
}
|
calendar.set(year, month, 1);
|
return calendar.getTime();
|
}
|
|
/**
|
* 返回指定日期的月的最后一天
|
*
|
* @return
|
*/
|
public static Date getLastDayOfMonth(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
|
1);
|
calendar.roll(Calendar.DATE, -1);
|
return calendar.getTime();
|
}
|
|
/**
|
* 返回指定年月的月的最后一天
|
*
|
* @param year
|
* @param month
|
* @return
|
*/
|
public static Date getLastDayOfMonth(Integer year, Integer month) {
|
Calendar calendar = Calendar.getInstance();
|
if (year == null) {
|
year = calendar.get(Calendar.YEAR);
|
}
|
if (month == null) {
|
month = calendar.get(Calendar.MONTH);
|
}
|
calendar.set(year, month, 1);
|
calendar.roll(Calendar.DATE, -1);
|
return calendar.getTime();
|
}
|
|
/**
|
* 返回指定日期的上个月的最后一天
|
*
|
* @return
|
*/
|
public static Date getLastDayOfLastMonth(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
calendar.set(calendar.get(Calendar.YEAR),
|
calendar.get(Calendar.MONTH) - 1, 1);
|
calendar.roll(Calendar.DATE, -1);
|
return calendar.getTime();
|
}
|
|
/**
|
* 返回指定日期的季的第一天
|
*
|
* @return
|
*/
|
public static Date getFirstDayOfQuarter(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
return getFirstDayOfQuarter(calendar.get(Calendar.YEAR),
|
getQuarterOfYear(date));
|
}
|
|
/**
|
* 返回指定年季的季的第一天
|
*
|
* @param year
|
* @param quarter
|
* @return
|
*/
|
public static Date getFirstDayOfQuarter(Integer year, Integer quarter) {
|
Calendar calendar = Calendar.getInstance();
|
Integer month = new Integer(0);
|
if (quarter == 1) {
|
month = 1 - 1;
|
} else if (quarter == 2) {
|
month = 4 - 1;
|
} else if (quarter == 3) {
|
month = 7 - 1;
|
} else if (quarter == 4) {
|
month = 10 - 1;
|
} else {
|
month = calendar.get(Calendar.MONTH);
|
}
|
return getFirstDayOfMonth(year, month);
|
}
|
|
/**
|
* 返回指定日期的季的最后一天
|
*
|
* @return
|
*/
|
public static Date getLastDayOfQuarter(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
return getLastDayOfQuarter(calendar.get(Calendar.YEAR),
|
getQuarterOfYear(date));
|
}
|
|
/**
|
* 返回指定年季的季的最后一天
|
*
|
* @param year
|
* @param quarter
|
* @return
|
*/
|
public static Date getLastDayOfQuarter(Integer year, Integer quarter) {
|
Calendar calendar = Calendar.getInstance();
|
Integer month = new Integer(0);
|
if (quarter == 1) {
|
month = 3 - 1;
|
} else if (quarter == 2) {
|
month = 6 - 1;
|
} else if (quarter == 3) {
|
month = 9 - 1;
|
} else if (quarter == 4) {
|
month = 12 - 1;
|
} else {
|
month = calendar.get(Calendar.MONTH);
|
}
|
return getLastDayOfMonth(year, month);
|
}
|
|
/**
|
* 返回指定日期的上一季的最后一天
|
*
|
* @return
|
*/
|
public static Date getLastDayOfLastQuarter(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
return getLastDayOfLastQuarter(calendar.get(Calendar.YEAR),
|
getQuarterOfYear(date));
|
}
|
|
/**
|
* 返回指定年季的上一季的最后一天
|
*
|
* @param year
|
* @param quarter
|
* @return
|
*/
|
public static Date getLastDayOfLastQuarter(Integer year, Integer quarter) {
|
Calendar calendar = Calendar.getInstance();
|
Integer month = new Integer(0);
|
if (quarter == 1) {
|
month = 12 - 1;
|
} else if (quarter == 2) {
|
month = 3 - 1;
|
} else if (quarter == 3) {
|
month = 6 - 1;
|
} else if (quarter == 4) {
|
month = 9 - 1;
|
} else {
|
month = calendar.get(Calendar.MONTH);
|
}
|
return getLastDayOfMonth(year, month);
|
}
|
|
/**
|
* 返回指定日期的季度
|
*
|
* @param date
|
* @return
|
*/
|
public static int getQuarterOfYear(Date date) {
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
return calendar.get(Calendar.MONTH) / 3 + 1;
|
}
|
|
/**
|
* java.sql.Timestamp
|
*
|
* @param date
|
* @return
|
*/
|
public static Timestamp getTimestamp(Date date) {
|
return new Timestamp(date.getTime());
|
}
|
|
/**
|
* string转 sql.timestamp
|
*
|
* @param dateStr
|
* @return
|
*/
|
public static Timestamp parseTimestamp(String dateStr) {
|
return parseTimestamp(dateStr, DATE_TIME_FORMAT1);
|
}
|
|
/**
|
* 格式化日期
|
*
|
* @param dateStr
|
* 字符型日期
|
* @param format
|
* 格式
|
* @return 返回日期
|
*/
|
public static Date parseDate(String dateStr, String format) {
|
Date date = null;
|
try {
|
DateFormat df = new SimpleDateFormat(format);
|
String dt = dateStr.replaceAll("-", "/");
|
if ((!dt.equals("")) && (dt.length() < format.length())) {
|
dt += format.substring(dt.length()).replaceAll("[YyMmDdHhSs]",
|
"0");
|
}
|
date = (Date) df.parse(dt);
|
} catch (Exception e) {
|
}
|
return date;
|
}
|
|
public static Timestamp parseTimestamp(String dateStr,
|
String format) {
|
Date date = parseDate(dateStr, format);
|
if (date != null) {
|
long t = date.getTime();
|
return new Timestamp(t);
|
} else
|
return null;
|
}
|
|
public static Timestamp parseTimestampSimple(String dateStr,
|
String format) {
|
Format f = new SimpleDateFormat(format);
|
Date d;
|
try {
|
d = (Date) f.parseObject(dateStr);
|
return new Timestamp(d.getTime());
|
} catch (ParseException e) {
|
return null;
|
}
|
}
|
|
/**
|
* 获取文件后缀名
|
*
|
* @param fileName
|
* @return
|
*/
|
public static String getFileExt(String fileName) {
|
if (fileName == null)
|
return "";
|
|
String ext = "";
|
String tempFileName = fileName.substring(fileName.lastIndexOf("/") + 1,
|
fileName.length());
|
int lastIndex = tempFileName.lastIndexOf(".");
|
if (lastIndex >= 0) {
|
ext = tempFileName.substring(lastIndex + 1).toLowerCase();
|
}
|
return ext;
|
}
|
|
public static int[] getDisRandomNum(int max, int length) {
|
int N = max;
|
List<Integer> list = new ArrayList<Integer>();
|
for (int i = 0; i < N; i++) {
|
list.add(i + 1);
|
}
|
int count = N;
|
int items[] = new int[N];
|
for (int i = 0; i < length; i++) {
|
//
|
int randomInt = new Random().nextInt(count);
|
items[i] = list.get(randomInt);
|
list.remove(randomInt);
|
count--;
|
// System.out.println(items[i]);
|
}
|
|
return items;
|
}
|
|
/**
|
* 获取星期几
|
*
|
*/
|
public static String getWeekday(long date) {
|
String result = "";
|
|
Calendar c = Calendar.getInstance();
|
c.setTime(new Date(date));
|
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
|
switch (dayOfWeek) {
|
case 1:
|
result = "星期日";
|
break;
|
case 2:
|
result = "星期一";
|
break;
|
case 3:
|
result = "星期二";
|
break;
|
case 4:
|
result = "星期三";
|
break;
|
case 5:
|
result = "星期四";
|
break;
|
case 6:
|
result = "星期五";
|
break;
|
case 7:
|
result = "星期六";
|
break;
|
}
|
|
return result;
|
}
|
|
public static String getFormatDateTimeFromUnixTime(Integer unixtime,
|
String format) {
|
String tmpdatestr = "";
|
try {
|
if ((unixtime != null) && (unixtime != 0)) {
|
Timestamp tmpdate = new Timestamp(unixtime * 1000L);
|
SimpleDateFormat tmpfmt = new SimpleDateFormat(format);
|
tmpdatestr = tmpfmt.format(tmpdate);
|
}
|
} catch (Exception ex) {
|
|
}
|
return tmpdatestr;
|
}
|
|
public static String getFormatDateTimeFromUnixTime(int unixtime,
|
String format) {
|
String tmpdatestr = "";
|
try {
|
if (unixtime != 0) {
|
Timestamp tmpdate = new Timestamp(unixtime * 1000L);
|
SimpleDateFormat tmpfmt = new SimpleDateFormat(format);
|
tmpdatestr = tmpfmt.format(tmpdate);
|
}
|
} catch (Exception ex) {
|
|
}
|
return tmpdatestr;
|
}
|
|
/**
|
* 获取当天前N天
|
*
|
* @param day
|
* @return
|
*/
|
public static String getCalendar(int day) {
|
Date dNow = new Date(); // 当前时间
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
String d = null;
|
if (day == 1) {
|
d = sdf.format(dNow) + " 00:00:00";
|
} else {
|
day = day - 1;
|
Date dBefore = new Date();
|
Calendar calendar = Calendar.getInstance(); // 得到日历
|
calendar.setTime(dNow);// 把当前时间赋给日历
|
calendar.add(Calendar.DAY_OF_MONTH, -day); // 设置为前一天
|
dBefore = calendar.getTime(); // 得到前一天的时间
|
d = sdf.format(dBefore) + " 00:00:00";
|
}
|
|
return d;
|
}
|
|
public static String getCalendarN(int day) {
|
Date dNow = new Date(); // 当前时间
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
String d = null;
|
if (day == 1) {
|
d = sdf.format(dNow);
|
} else {
|
day = day - 1;
|
Date dBefore = new Date();
|
Calendar calendar = Calendar.getInstance(); // 得到日历
|
calendar.setTime(dNow);// 把当前时间赋给日历
|
calendar.add(Calendar.DAY_OF_MONTH, -day); // 设置为前一天
|
dBefore = calendar.getTime(); // 得到前一天的时间
|
d = sdf.format(dBefore);
|
}
|
|
return d;
|
}
|
|
public static String getIpAddr(HttpServletRequest request) {
|
String ip = request.getHeader("X-Forwarded-For");
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("Proxy-Client-IP");
|
}
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("WL-Proxy-Client-IP");
|
}
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_CLIENT_IP");
|
}
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
}
|
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getRemoteAddr();
|
}
|
return ip;
|
}
|
|
/**
|
* 获取当前时间
|
*
|
* @return
|
*/
|
public static String getDay() {
|
Date now = new Date();
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
return sdf.format(now);
|
}
|
|
public static String getDataTime(String str) {
|
Date now = new Date();
|
SimpleDateFormat sdf = new SimpleDateFormat(str);
|
return sdf.format(now);
|
}
|
|
/*
|
* 获取请求头部的类型
|
*/
|
public static String getContentType(HttpServletRequest request) {
|
Enumeration e = request.getHeaderNames();
|
while (e.hasMoreElements()) {
|
String name = (String) e.nextElement();
|
String value = request.getHeader(name);
|
if("content-type".equals(name)){
|
|
log.info("request type is: " + value);
|
|
if(value.contains("text/plain") || value.contains("application/x-www-form-urlencoded")){
|
return TEXT;
|
}
|
else if(value.contains("application/json")){
|
return JSON;
|
}
|
|
}
|
}
|
return "";
|
}
|
|
/**
|
* @descript:计算两个字符串日期相差的天数
|
* @param date1 字符串日期1
|
* @param date2 字符串日期2
|
* @param format 日期格式化方式 format="yyyy-MM-dd"
|
* @return
|
*/
|
public static long dayDiffString(String date1, String date2,String format) {
|
SimpleDateFormat formater = new SimpleDateFormat(format);
|
long diff=0l;
|
try {
|
long d1 = formater.parse(date1).getTime();
|
long d2 = formater.parse(date2).getTime();
|
//diff=(Math.abs(d1-d2) / (1000 * 60 * 60 * 24));
|
diff=(d1-d2)/(1000 * 60 * 60 * 24);
|
} catch (ParseException e) {
|
e.printStackTrace();
|
}
|
return diff;
|
}
|
|
/**
|
* 相差多少天
|
* @param bigDay,SmallDay
|
* @return
|
*/
|
public static Long time_difference(Date bigDay,Date SmallDay){
|
try{
|
long diff = bigDay.getTime() - SmallDay.getTime();
|
long days = diff / (1000 * 60 * 60 * 24);
|
return days;
|
}catch (Exception e){
|
return null;
|
}
|
}
|
|
public static String getUTF8String(String source) {
|
String tmpret = "";
|
try {
|
if (source.indexOf("\\x") != -1) {
|
String sourceArr[] = source.split("\\\\"); // 分割拿到形如 xE9 的16进制数据
|
if (sourceArr.length > 1) {
|
byte[] byteArr = new byte[sourceArr.length - 1];
|
for (int i = 1; i < sourceArr.length; i++) {
|
Integer hexInt = Integer.decode("0" + sourceArr[i]);
|
byteArr[i - 1] = hexInt.byteValue();
|
}
|
tmpret = new String(byteArr, "UTF-8");
|
} else
|
tmpret = source;
|
} else
|
tmpret = source;
|
byte[] utf8 = tmpret.getBytes("UTF-8");
|
tmpret = new String(utf8, "UTF-8");
|
//System.out.println(tmpret);
|
|
} catch (Exception ex) {
|
System.out.println(ex);
|
}
|
return tmpret;
|
}
|
|
public static String getRandomStr(int length){
|
// ,"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v"
|
String[] array = {"0","1","2","3","4","5","6","7","8","9"};
|
Random rand = new Random();
|
for (int i = 10; i > 1; i--) {
|
//将数组下标随机排列
|
int index = rand.nextInt(i);
|
String tmp = array[index];
|
array[index] = array[i - 1];
|
array[i - 1] = tmp;
|
}
|
StringBuffer sb = new StringBuffer();
|
//循环取出六位数
|
for(int i = 0; i < length;i++){
|
sb.append(array[i]);
|
}
|
return sb.toString();
|
}
|
|
/**
|
* 小数保留位数 四舍六入五成双
|
*/
|
public static String getDigit(int scale) {
|
String str = "#.#";
|
for (int i = 0; i < scale - 1; i++) {
|
str += "#";
|
}
|
if (scale == 0) {
|
str = "#";
|
}
|
return str;
|
}
|
|
public static Double getDbData(Double value, int scale) {
|
DecimalFormat df = new DecimalFormat(getDigit(scale));
|
Double val = Double.parseDouble(df.format(value));
|
return val;
|
}
|
|
|
// public static List<FileItem> getFileItemList(HttpServletRequest request){
|
// String TEMPPATH = Config.get("uploadtemppath") + convertDateToString(new Date(), SafeUtils.DATE_FORMAT1) + "/";
|
// List<FileItem> fileItems = null;
|
// FileHelper.checkPathExist(TEMPPATH );
|
// int maxFileSize = 10000 * 1024 * 1000;
|
// int maxMemSize = 10000 * 1024 * 1000;
|
// DiskFileItemFactory factory = new DiskFileItemFactory();
|
// // 设置内存中存储文件的最大值
|
// factory.setSizeThreshold(maxMemSize);
|
// // 本地存储的数据大于 maxMemSize.
|
// File tempfile = new File(TEMPPATH);
|
// factory.setRepository(tempfile);
|
// // 创建一个新的文件上传处理程序
|
// ServletFileUpload upload = new ServletFileUpload(factory);
|
// // 设置最大上传的文件大小
|
// upload.setSizeMax(maxFileSize);
|
// // 解析获取的文件
|
// try {
|
// fileItems = upload.parseRequest(request);
|
// } catch (FileUploadException e) {
|
// // TODO Auto-generated catch block
|
// e.printStackTrace();
|
// }
|
// return fileItems;
|
// }
|
|
/*
|
* 转换日期,yyyyMMdd-->yyyy-MM-dd
|
*/
|
public static String convertSplitdate(String bookkeepdate){
|
String convertdate = "";
|
if(bookkeepdate.length() == 8){
|
convertdate = bookkeepdate.substring(0,4)+"-"+bookkeepdate.substring(4,6)+"-"+bookkeepdate.substring(6,8);
|
}
|
return convertdate;
|
}
|
|
/**
|
* 日期转换星期几
|
*
|
* @param date 需要转换的日期
|
* @return
|
*/
|
public static Integer dateToWeek(Date date) {
|
// String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
|
Integer[] weekDays = {1, 2, 3, 4, 5, 6, 7};
|
Calendar cal = Calendar.getInstance();
|
cal.setFirstDayOfWeek(Calendar.MONDAY);
|
cal.setTime(date);
|
// 指示一个星期中的某天,0代表星期天。
|
int w = Math.max(cal.get(Calendar.DAY_OF_WEEK) - 1, 0);
|
return weekDays[w];
|
}
|
|
public static String localdateToWeek(LocalDate date){
|
String[][] strArray = {{"MONDAY", "MON"}, {"TUESDAY", "TUE"}, {"WEDNESDAY", "WED"}, {"THURSDAY", "THU"}, {"FRIDAY", "FRI"}, {"SATURDAY", "SAT"}, {"SUNDAY", "SUN"}};
|
// LocalDate currentDate = LocalDate.now();
|
String k = String.valueOf(date.getDayOfWeek());
|
//获取行数
|
for (int i = 0; i < strArray.length; i++) {
|
if (k.equals(strArray[i][0])) {
|
k = strArray[i][1];
|
break;
|
}
|
}
|
return k;
|
}
|
|
|
/**
|
* 当前时间所在一周的周一和周日时间
|
* @param
|
* @return
|
*/
|
public static Map<String,String> getWeekDate() {
|
Map<String,String> map = new HashMap();
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
|
Calendar cal = Calendar.getInstance();
|
cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
|
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
|
if(dayWeek==1){
|
dayWeek = 8;
|
}
|
// System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期
|
|
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
|
Date mondayDate = cal.getTime();
|
String weekBegin = sdf.format(mondayDate);
|
// System.out.println("所在周星期一的日期:" + weekBegin);
|
|
map.put("1", weekBegin);
|
Calendar c=Calendar.getInstance();
|
c.setTime(mondayDate);
|
for(int i=1;i<7;i++){
|
c.add(Calendar.DAY_OF_MONTH,1);
|
Date d=c.getTime();
|
map.put(String.valueOf(i+1),sdf.format(d));
|
}
|
return map;
|
}
|
|
/**
|
* 得到几个月之后的时间
|
*
|
* @param date
|
* @param month
|
* @return
|
*/
|
public static Date addMonthDate(Date date, int month, String pattern) throws ParseException {
|
String nowDate = null;
|
SimpleDateFormat format = new SimpleDateFormat(pattern);
|
// Date parse = format.parse(date);
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(date);
|
calendar.add(Calendar.MONTH, month);
|
nowDate = format.format(calendar.getTime());
|
|
return convertStringToDate(nowDate, pattern);
|
}
|
|
/**
|
* 得到几天后的时间
|
*
|
* @param d
|
* @param day
|
* @return
|
*/
|
public static Date addDays(Date d, int day) {
|
Calendar now = Calendar.getInstance();
|
now.setTime(d);
|
now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
|
return now.getTime();
|
}
|
|
/**
|
* 得到几分之后的时间
|
*
|
* @param date
|
* @param minute
|
* @param pattern
|
* @return
|
*/
|
public static String addMinuteDate(String date, int minute, String pattern) {
|
String nowDates = null;
|
SimpleDateFormat formats = new SimpleDateFormat(pattern);
|
try {
|
Date parse = formats.parse(date);
|
Calendar calendar = Calendar.getInstance();
|
calendar.setTime(parse);
|
calendar.add(Calendar.MINUTE, minute);
|
nowDates = formats.format(calendar.getTime());
|
} catch (ParseException e) {
|
log.error(e.getMessage());
|
}
|
return nowDates;
|
}
|
|
public static String lastMonthDate(String date) {
|
Calendar c = Calendar.getInstance();
|
try {
|
c.setTime(SafeUtils.convertStringToDate(date, SafeUtils.DATE_FORMAT));
|
} catch (ParseException e) {
|
e.printStackTrace();
|
}
|
c.add(Calendar.MONTH, -1);
|
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
|
String preMonth = dateFormat.format(c.getTime());
|
return preMonth;
|
}
|
|
// 将request中的参数转换成Map
|
public static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
|
Map<String, String> retMap = new HashMap<String, String>();
|
|
Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
|
|
for (Map.Entry<String, String[]> entry : entrySet) {
|
String name = entry.getKey();
|
String[] values = entry.getValue();
|
int valLen = values.length;
|
|
if (valLen == 1) {
|
retMap.put(name, values[0]);
|
} else if (valLen > 1) {
|
StringBuilder sb = new StringBuilder();
|
for (String val : values) {
|
sb.append(",").append(val);
|
}
|
retMap.put(name, sb.toString().substring(1));
|
} else {
|
retMap.put(name, "");
|
}
|
}
|
|
return retMap;
|
}
|
|
|
public static void main(String[] args) throws ParseException {
|
|
// System.out.println(convertIntegerToString(SafeUtils.getCurrentUnixTime() + 7*24*3600, DATE_FORMAT1));
|
System.out.println(getWeekDate());
|
// System.out.println(getDisRandomNum(10,4));
|
//
|
// int num =2;
|
//
|
// switch (num){
|
//
|
// case 1:
|
// int mm = 3;
|
// String ssss = "22";
|
// Object sss = new Object();
|
// System.out.println("111");
|
// break;
|
// case 2:
|
// ssss = "aaaa";
|
// sss = new Object();
|
// System.out.println(ssss);
|
// System.out.println("222");
|
// break;
|
//
|
// }
|
|
}
|
|
|
|
|
}
|