java时间转换工具

时间转换工具
①字符串转时间对象

②时间对象转字符串

③时间戳转时间对象

④时间对象转时间戳

⑤时间戳转一周的坐标位置

 

public class TimeExchangeUtil {

    /**
     * Data类型转换为String类型
     *
     * @param date    date
     * @param pattern 时间格式
     * @return String
     */
    public static String dateToStr(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * String类型转换为Data类型
     *
     * @param str     str
     * @param pattern 时间格式
     * @return String
     */
    public static Date strToDate(String str, String pattern) {
        if (null == str) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = sdf.parse(str);
        } catch (ParseException e) {
            LOGGER.error("时间转换错误!", e);
        }
        return date;
    }

    /**
     * 将时间戳转换为时间
     */
    public static String stampToDate(String stamp, String pattern) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        long lt = new Long(stamp);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String dateTime, String pattern) {
        String res = "";
        String regex = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}";
        boolean result = Pattern.compile(regex).matcher(dateTime).matches();
        if (!result) {
            LOGGER.error("时间转换错误!");
        }
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
            Date date = null;
            date = simpleDateFormat.parse(dateTime);
            long ts = date.getTime();
            res = String.valueOf(ts);
        } catch (ParseException e) {
            LOGGER.error("时间转换错误!");
        }
        return res;
    }

}

 

posted @ 2018-04-13 11:11  dream_on_sakura_rain  阅读(309)  评论(0编辑  收藏  举报