欢迎使用CSDN-markdown编辑器

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

import com.alibaba.fastjson.JSON;

/**
*
* @ClassName: Toolkit
* @Description: TODO(工具类)
* @author llj
* @date 2013年01月25日 下午3:41:47
*
*/
public class Toolkit {
public static String dateTimePattern = “yyyy-MM-dd HH:mm:ss”;
public static String datePattern = “yyyy-MM-dd”;
public static final String SHORTPATTERN = “yyyyMMdd”;

/**
 * 判断是否为空的方法
 * 
 * @param obj
 * @return
 */
public static boolean isEmpty(Object obj) {
    return obj == null || "null".equals(obj) || "undefined".equals(obj)
            || "".equals(obj.toString().trim());
}


/**
 * 转化JSON
 * 
 * @param obj
 * @param pattern
 * @return
 */
public static String toJson(Object obj, String pattern) {
    if (Toolkit.isEmpty(pattern)) {
        pattern = Toolkit.datePattern;
    }
    return JSON.toJSONStringWithDateFormat(obj, pattern);
}

/**
 * 解析JSON 转化成列表
 * 
 * @param json
 * @param clazz
 * @return
 */
public static <T> List<T> jsonToList(String json, Class<T> clazz) {
    return JSON.parseArray(json, clazz);
}

/**
 * 解析JSON转化成JAVABEAN
 * 
 * @param json
 * @param clazz
 * @return
 */
public static <T> T jsonToObject(String json, Class<T> clazz) {
    return JSON.parseObject(json, clazz);
}
/**
 * 根据日期与随机数,生成随机字符串
 * 
 * @return
 */
public static String RandomStr() {
    DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
    String formatDate = format.format(new Date());
    // 随机生成文件编号
    int random = new Random().nextInt(10000);
    return new StringBuffer().append(formatDate).append(random).toString();
}

/**
 * 获取不带时间的Date
 * 
 * @param date
 * @return
 * @throws ParseException
 */
public static Date getDateWithoutTime(Date date) throws ParseException {
    DateFormat fmt = new SimpleDateFormat(datePattern);
    return fmt.parse(fmt.format(date));
}

public static Date getDateByShortDateStr(String dateStr){
    DateFormat fmt = new SimpleDateFormat(SHORTPATTERN);
    Date date = null;
    try {
         date= fmt.parse(dateStr);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return date;
}

/**
 * 获取带时间的Date
* @Title: getDateWithTime 
* @Description: TODO() 
* @param @param date
* @param @return
* @param @throws ParseException    设定文件 
* @return Date    返回类型 
* @throws
 */
public static Date getDateWithTime(Date date) throws ParseException {
    DateFormat fmt = new SimpleDateFormat(dateTimePattern);
    return fmt.parse(fmt.format(date));
}

/**
 * 获取当前日期(不带时间)
 * 
 * @return
 * @throws ParseException
 */
public static Date getCurrDateWithoutTime() throws ParseException {
    return getDateWithoutTime(new Date());
}


/**
 * 获取当前日期的字符串
 * @return String (yyyy-MM-dd)
 *
 */
public static String getCurrDateWithoutTimeStr() {
    DateFormat fmt = new SimpleDateFormat(datePattern);
    return fmt.format(new Date());
}
public static String getCurrDateWithoutTimeStr2() {
    DateFormat fmt = new SimpleDateFormat(dateTimePattern);
    return fmt.format(new Date());
}

/**
 * 获取当前日期
* @Title: getCurrDateWithTimeStr 
* @Description: TODO() 
* @param @return    设定文件 
* @return String    String (yyyy-MM-dd HH:mm:ss)
* @throws
 */
public static String getCurrDateWithTimeStr() {
    DateFormat fmt = new SimpleDateFormat(dateTimePattern);
    return fmt.format(new Date());
}

/**
 * 获取两个时间之间的时间差
 */
public static long getDiffBetweenDate(String begin, String end) {
    DateFormat format = new SimpleDateFormat(dateTimePattern);
    Date beginDate = null;
    Date endDate = null;
    long diff = 0;
    try {
        beginDate = format.parse(begin);
        endDate = format.parse(end);
        diff = endDate.getTime() - beginDate.getTime();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return diff;
}

/**
 * 格式化日期
 * 
 * @param dateStr
 * @param pattern
 * @return
 * @throws ParseException
 */
public static Date formatDate(String dateStr, String pattern)
        throws ParseException {
    if (Toolkit.isEmpty(pattern)) {
        pattern = Toolkit.datePattern;
    }
    DateFormat fmt = new SimpleDateFormat(pattern);
    return fmt.parse(dateStr);
}

/**
 * 返回格式化后的日期
 * 
 * @param date
 * @param pattern
 * @return
 */
public static String parseDate(Date date, String pattern) {
    if (Toolkit.isEmpty(pattern)) {
        pattern = Toolkit.datePattern;
    }
    DateFormat fmt = new SimpleDateFormat(pattern);
    return fmt.format(date);
}

/**
 * 创建MAP 并放入条件
 * 
 * @param key
 * @param value
 * @return
 */
public static HashMap<String, Object> initMapCondition(String key,Object value) {
    HashMap<String, Object> result = new HashMap<>();
    result.put(key, value);
    return result;
}

/**
 * 创建一个MAP 并放入key为status,value为输入值
 * 
 * @param status
 * @return
 */
public static HashMap<String, Object> initMapStatus(Integer status) {
    return Toolkit.initMapCondition("status", status);
}

public static void main(String[] args) {
    Map<String, Object> map = new HashMap<>();
    map.put("user_name", "admin");
    map.put("phone", "13558657902");
    List<Map<String, Object>> list = new ArrayList<>();
    list.add(map);
    System.out.println(JSON.toJSON(new ExtReturn(1, "成功", "{}")));
}

/**
 * 随机32位UUID
 * 
 * @return
 */
public static String randomUUID() {
    UUID uuid = UUID.randomUUID();
    String result = uuid.toString().replaceAll("-", "");
    return result;
}

/**
 * 生成带页码信息的pageBean
 * 
 * @param info
 * @return
 */
public static PageBean fillPageInfo(PageInfo info) {
    PageBean page = new PageBean();
    page.setPageSize(info.getRows() == null ? 20 : info.getRows());
    page.setPageNumber(info.getPage() == null ? 1 : info.getPage());
    if (!Toolkit.isEmpty(info.getConditions())) {
        page.setConditions(info.getConditions());
    }
    return page;
}

/** 
* @Title: getLaterTimeThanSpecifyTime 
* @Description: TODO(获取距离给定时间之后的某一个时间) 
* @param @param specifyTime
* @param @param field 为Calendar类静态常量
* @param @param amount 为时间间隔类型
* @param @return    设定文件 
* @return String    返回类型 
* @throws 
*/
public static String getLaterTimeThanSpecifyTime(Calendar specifyTime, int field, int amount){
    specifyTime.add(field, amount);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateTimePattern);
    return simpleDateFormat.format(specifyTime.getTimeInMillis());
}

/**
 * 
* @Title: getServiceTime 
* @Description: TODO(java 获取1970到现在毫秒数) 
* @param @return    设定文件 
* @return Map<String,Object>    返回类型 
* @throws
 */
public static Map<String, Object> getServiceTime() {
    Map<String, Object> timeMap = new HashMap<>();

    Calendar c=Calendar.getInstance();

// c.set(year,month,date,hour,minute,second);
long answer=c.getTimeInMillis()/1000;

// Date date = new Date();
// date.getTime();
timeMap.put(“dateTime”, answer);

    return timeMap;
}

/**
 * @Title: objectMapToStringMap
 * @Description: obj Map 转  str Map 
 * 
 * @param obj 需要被转化的Map
 * @return String map
 */
public static Map<String,String> objectMapToStringMap(Map<String, Object> obj){

    Map<String,String> strMap = new HashMap<>();

    Set<String> keySet = obj.keySet();

    for(String key : keySet){
        strMap.put(key, obj.get(key).toString());
    }

    return strMap;
}

/**
 * @Title: stringMapToObjectMap
 * @Description: str Map 转  obj Map 
 * 
 * @param obj 需要被转化的Map
 * @return obj map
 */
public static Map<String,Object> stringMapToObjectMap(Map<String, String> obj){

    Map<String,Object> objMap = new HashMap<>();

    Set<String> keySet = obj.keySet();

    for(String key : keySet){
        objMap.put(key, obj.get(key));
    }

    return objMap;
}

public static void main(String[] args) {
DateTime dTime = new DateTime();
DateTime dateTime = null;
try {
dateTime = new DateTime(Toolkit.formatDate(“2014-04-20 16:38:35”, Toolkit.dateTimePattern));
} catch (ParseException e) {
e.printStackTrace();
}
Days days = Days.daysBetween(dateTime, dTime);
Hours hours = Hours.hoursBetween(dateTime, dTime);
Minutes minutes = Minutes.minutesBetween(dateTime, dTime);
System.out.println(days.getDays() + “=====days”);
System.out.println(hours.getHours() + “=====hours”);
System.out.println(minutes.getMinutes() + “=====minutes”);
}

/**
 * 
 * @Title: getConstellation
 * @Description: 根据生日计算出星座
 * 
 */
public static String getConstellation(Object birthday) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String format = sdf.format(birthday);
    int month = Integer.parseInt(format.substring(4, 6));
    int day = Integer.parseInt(format.substring(6, 8));
    int[] DAYARR = new int[] { 20, 19, 21, 20, 21, 22, 23, 23, 23, 24, 23, 22 };
    String[] CONSTELLATIONARR = new String[] { "摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座",
            "天蝎座", "射手座", "摩羯座" };
    return day < DAYARR[month - 1] ? CONSTELLATIONARR[month - 1] : CONSTELLATIONARR[month];
}

/**
 * 
 * @Title: getYearDiff
 * @Description: 计算用户年龄
 * 
 */
public static Map<String, Object> getYearDiff(Map<String, Object> params, String paramName) {
    if (!params.containsKey(paramName)) {
        params.put("age", 18);
    } else {
        try {
            DateTime dateTime = new DateTime(new Date());
            Date date = Toolkit.formatDate(params.get(paramName).toString(), "yyyyMMdd");
            DateTime startTime = new DateTime(date);
            Interval interval = new Interval(startTime, dateTime);
            Period period = interval.toPeriod();
            int years = period.getYears();
            years = years == 0 ? 18 : years;
            // Years years = Years.yearsBetween(startTime, dateTime);
            params.put("age", years);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return params;
}

public static ClubMotionValueDetail getTimeDiff(ClubMotionValueDetail params, String paramName) {
    DateTime dateTime = new DateTime(new Date());
    DateTime time = null;
    try {
        time = new DateTime(Toolkit.formatDate(params.getBeginTime(), Toolkit.dateTimePattern));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Interval interval = new Interval(time, dateTime);
    Period period = interval.toPeriod();
    int day = period.getDays();
    int hour = period.getHours();
    int minute = period.getMinutes();
    // int days = Days.daysBetween(time, dateTime).getDays();
    // int hours = Hours.hoursBetween(time, dateTime).getHours()%24;
    // int minutes = Minutes.minutesBetween(time, dateTime).getMinutes()%60;
    if (day != 0) {
        if (day == 1) {
            params.setBeginTime("昨天  " + time.toString("HH:mm", Locale.CHINESE));
        } else {
            return params;
        }
    } else if (day == 0 && hour != 0) {
        params.setBeginTime(hour + "小时前");
    } else {
        params.setBeginTime(minute + "分钟前");
    }
    return params;
}

/**
 * @Title: getBirthDayStr
 * @Description: 根据日期获取中文的生日日期
 * 
 * @param birthday
 *            生日格式可为(yyyy-MM-dd 或者 yyyy-MM-dd HH:mm:ss)
 * @return
 */
public static String getBirthDayStr(String birthday) {

    StringBuilder builder = new StringBuilder();
    builder.append(birthday.substring(5, 7)).append("月");
    builder.append(birthday.substring(8, 10)).append("日");

    return builder.toString();

}

/**
 * @Title: getTimeDiffFromMap @Description: 用于达人计算登录时间差 @param @param
 * params @param @param date @param @param paramName @param @return
 * 设定文件 @return Map<String,Object> 返回类型 @throws
 */
public static Map<String, Object> getTimeDiffFromMap(Map<String, Object> params, Date date, String paramName) {
    DateTime dateTime = new DateTime(date);
    DateTime time = new DateTime((Date) params.get(paramName));
    Interval interval = new Interval(time, dateTime);
    Period period = interval.toPeriod();
    int day = period.getDays();
    int hour = period.getHours();
    int minute = period.getMinutes();
    // Days days = Days.daysBetween(time, dateTime);
    // Hours hours = Hours.hoursBetween(time, dateTime);
    // Minutes minutes = Minutes.minutesBetween(time, dateTime);
    if (day != 0) {
        if (day > 7) {
            params.replace(paramName, params.get(paramName));
        } else {
            params.replace(paramName, day + "天前");
        }
    } else if (day == 0 && hour != 0) {
        params.replace(paramName, hour + "小时前");
    } else {
        params.replace(paramName, minute + "分钟前");
    }
    return params;
}

}

你可能感兴趣的:(Java常用工具类)