Java-日期处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31150365/article/details/85250967
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Time;
import java.text.*;
import java.util.*;


/**
 * 日期处理
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    private final static Logger logger = LoggerFactory.getLogger(DateUtils.class);
    /**
     * 时间格式(yyyy-MM-dd)
     */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /**
     * 时间格式(HH:mm:ss)
     */
    public final static String DATE_TIME = "HH:mm:ss";
    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static String format(Date date) {
        return format(date, DATE_PATTERN);
    }

    public static String format_time(Date date) {
        return format(date, DATE_TIME);
    }

    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 计算距离现在多久,非精确
     *
     * @param date
     * @return
     */
    public static String getTimeBefore(Date date) {
        Date now = new Date();
        long l = now.getTime() - date.getTime();
        long day = l / (24 * 60 * 60 * 1000);
        long hour = (l / (60 * 60 * 1000) - day * 24);
        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        String r = "";
        if (day > 0) {
            r += day + "天";
        } else if (hour > 0) {
            r += hour + "小时";
        } else if (min > 0) {
            r += min + "分";
        } else if (s > 0) {
            r += s + "秒";
        }
        r += "前";
        return r;
    }

    /**
     * 计算距离现在多久,精确
     *
     * @param date
     * @return
     */
    public static String getTimeBeforeAccurate(Date date) {
        Date now = new Date();
        long l = now.getTime() - date.getTime();
        long day = l / (24 * 60 * 60 * 1000);
        long hour = (l / (60 * 60 * 1000) - day * 24);
        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        String r = "";
        if (day > 0) {
            r += day + "天";
        }
        if (hour > 0) {
            r += hour + "小时";
        }
        if (min > 0) {
            r += min + "分";
        }
        if (s > 0) {
            r += s + "秒";
        }
        r += "前";
        return r;
    }


    /**
     * String转Time格式HH:mm:ss
     *
     * @param
     */
    public static Time strToTime(String strDate) {
        String str = strDate;
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        Date d = null;
        try {
            d = format.parse(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Time time = new Time(d.getTime());
        return Time.valueOf(str);
    }


    /**
     * Date转String yyyy-MM-dd
     */

    public static String dateToString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String STD = sdf.format(date);
        return STD;
    }

    /**
     * Date转String yyyy-MM-dd
     */

    public static String dateToStrMM(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM");
        String STD = sdf.format(date);
        return STD;
    }

    /**
     * Date转String yyyy-MM-dd  HH:mm:ss
     */

    public static String dateToStr(Date date) {
        if ("".equals(date) || null == date) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String STD = sdf.format(date);
        return STD;
    }

    /**
     * Date转String yyyyMMdd
     */

    public static String dateToStringyMd(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String STD = sdf.format(date);
        return STD;
    }

    /**
     * Date转StringHH:mm:ss
     */

    public static String dateToStringHMS(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String STD = sdf.format(date);
        return STD;
    }
    /**
     * Date转StringHH:mm:
     */

    public static String dateToStringHH(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String STD = sdf.format(date);
        return STD;
    }

    /**
     * String 转Date yyyy-MM-dd
     */
    public static Date stringToDate(String str)  {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date DTS = sdf.parse(str);
            return DTS;
        }catch (Exception e){
            e.getMessage();
        }
        return null;
    }

    /**
     * String 转Date yyyy-MM-dd HH:mm:ss
     */
    public static Date stringToDateTime(String str) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date DTS = sdf.parse(str);
            return DTS;
        }catch (Exception e){
            e.getMessage();
        }
        return null;
    }

    public static Date stringToDateTime1(String str) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date DTS = sdf.parse(str);
        return DTS;
    }
    public static Date stringToDat(String str,String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date DTS = null;
        try {
            DTS = sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return DTS;
    }

    /**
     * String 转Date dd/MM/yyyy
     */
    public static String dateToStringInturn(Date date) {
        if ("".equals(date) || null == date) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String STD = sdf.format(date);
        return STD;
    }

    /**
     * 将字符串格式yyyyMMdd的字符串转为日期,格式"yyyy-MM-dd"
     *
     * @param date 日期字符串
     * @return 返回格式化的日期
     * @throws ParseException 分析时意外地出现了错误异常
     */
    public static String strToDateFormat(String date) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        formatter.setLenient(false);
        Date newDate = formatter.parse(date);
        formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(newDate);
    }

    /**
     * 获取指定日期 未来 past天的日期
     *
     * @param data 指定日期  data是指定日期 例如20170608
     * @param past 几天后日期   例如   7
     * @return 日期    20170615
     */
    public static String getFetureDate(String data, int past) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // 将字符串的日期转为Date类型,ParsePosition(0)表示从第一个字符开始解析
        Date date = sdf.parse(data, new ParsePosition(0));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        String result = sdf.format(today);
        return result;
    }

    /**
     * 获取指定日期 未来 past天的日期
     *
     * @param data 指定日期  data是指定日期 例如2017-06-08
     * @param past 几天后日期   例如   7
     * @return 日期    2017-06-15
     */
    public static String getFetureDate1(String data, int past) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 将字符串的日期转为Date类型,ParsePosition(0)表示从第一个字符开始解析
        Date date = sdf.parse(data, new ParsePosition(0));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        String result = sdf.format(today);
        return result;
    }


    /**
     * 获取指定日期 未来 past天的日期
     *
     * @param data
     * @param past 几天后日期   例如   7
     * @return 日期
     */
    public static Date getAfterDate(Date data, int past) {
        Format f = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(data);
        // 今天past天
        c.add(Calendar.DAY_OF_MONTH, past);
        Date tomorrow = c.getTime();
        return tomorrow;
    }

    public static String getTiemAfter(Long time) {
        long hours = time / (1000 * 60 * 60);
        long minutes = (time - hours * (1000 * 60 * 60)) / (1000 * 60);
        long ss = (time - minutes * (1000 * 60 * 60)) / (1000 * 60) / (1000 * 60);
        String diffTime = "";
        String hours1 = String.valueOf(hours);
        if (hours < 10) {
            hours1 = "0" + hours;
        }
        if (minutes < 10 && ss < 10) {
            diffTime = hours1 + ":0" + minutes + ":0" + ss;
        } else {
            diffTime = hours1 + ":" + minutes + ":" + ss;
        }


        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");//初始化Formatter的转换格式。

        String hms = formatter.format(time);
        return diffTime;

    }

    /**
     * String转Date   HH:mm
     *
     * @param dateStr
     * @return
     */
    public static Date StringToDate(String dateStr) {
        String FORMATSTR = "HH:mm";
        DateFormat sdf = new SimpleDateFormat(FORMATSTR);
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 将字符串格式yyyyMMdd的月份加一"
     *
     * @param date
     * @return 返回月份加一日期字符串
     * @throws Exception 分析时意外地出现了错误异常
     */
    public static String monthAddOne(String date) {
        int dateTime = Integer.parseInt(date);
        dateTime = dateTime + 100;
        date = String.valueOf(dateTime);
        return date;
    }

    public static String getDatePoor(String endDateStr, String nowDateStr) {
        try {
            Date endDate = stringToDateTime1(nowDateStr);
            Date nowDate = stringToDateTime1(endDateStr);
            long nd = 1000 * 24 * 60 * 60;
            long nh = 1000 * 60 * 60;
            long nm = 1000 * 60;
            // long ns = 1000;
            // 获得两个时间的毫秒时间差异
            long diff = endDate.getTime() - nowDate.getTime();
            // 计算差多少天
            long day = diff / nd;
            // 计算差多少小时
            long hour = diff % nd / nh;
            // 计算差多少分钟
            long min = diff % nd % nh / nm;
            // 计算差多少秒//输出结果
            // long sec = diff % nd % nh % nm / ns;
            return String.valueOf(hour);
        } catch (Exception e) {
            e.getMessage();
        }
        return null;
    }

    /**
     * 日期添加天数
     *
     * @param date 日期
     * @param day  天数
     * @return
     */
    public static Date addDay(Date date, int day) {
        return addDays(date, day);
    }

    /**
     * 设置日期时分秒
     *
     * @param date
     * @param hours
     * @param minutes
     * @param seconds
     * @return
     */
    public static Date setTime(Date date, int hours, int minutes, int seconds) {
        return setSeconds(setMinutes(setHours(date, hours), minutes), seconds);
    }
    /**
     * 日期格式校验 true 格式错误
     *
     * @param str
     * @return
     */
    public static boolean isValidDate(String str,String pattern) {
        boolean convertSuccess = false;
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess = true;
        }
        return convertSuccess;
    }

    /**
     * 日期格式校验 true 格式错误
     *
     * @param str
     * @return
     */
    public static boolean isValidDate(String str) {
        boolean convertSuccess = false;
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess = true;
        }
        return convertSuccess;
    }

    /**
     * 日期格式校验 true 格式错误
     *
     * @param str
     * @return
     */
    public static boolean isValidTime(String str) {
        boolean convertSuccess = false;
        // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
            convertSuccess = true;
        }
        return convertSuccess;
    }

    /**
     * 获取两个日期之间的日期
     *
     * @param start 开始日期  yyyy-MM-dd  HH:mm:ss
     * @param end   结束日期
     * @return 日期集合
     */
    public static List<Date> getBetweenDates(Date start, Date end) {
        List<Date> result = new ArrayList<Date>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
        tempStart.add(Calendar.DAY_OF_YEAR, 0);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        while (tempStart.before(tempEnd)) {
            result.add(tempStart.getTime());
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }
    /**
     * 获取两个日期之间的日期
     *
     * @param start 开始日期  yyyy-MM- dd
     * @param end   结束日期
     * @return 日期集合
     */
    public static List<String> BetweenDates(Date start, Date end) {
        List<String> result = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String forStart = format.format(start); // 设置日期格式
        String forEnd = format.format(end);
        //将string类型
        Date start1 = null;
        Date end1 = null;
        try {
            start1 = format.parse(forStart);
            end1 = format.parse(forEnd);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start1);
        tempStart.add(Calendar.DAY_OF_YEAR, 0);
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end1);

        while (tempStart.before(tempEnd)) {
            String datechange = datechange(tempStart.getTime(), "yyyy-MM-dd");
            result.add(datechange);
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }
    public static String datechange(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String demo = sdf.format(date);
        return demo;
    }


    /**
     * 由时间戳获取时间 yyyy-MM-dd HH:mm:ss
     *
     * @param timestamp
     * @return
     */
    public static String getDateFromTimestamp(Long timestamp, String pattern) {
        Date date = new Date(timestamp);
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String datetime = format.format(date);
        return datetime;
    }

    /**
     * 获取某月的每个整周对应的日期
     * @param monthDay yyyy-MM-dd
     * @return
     * @throws Exception
     */
    public static Map<Integer, Map<Date, Date>> getWeekDay(String monthDay) throws Exception {
        if (StringUtils.isEmpty(monthDay)) {
            return null;
        }
        //key 为某月的第几周 value为这周周一、周日对应的日期map 例如:{1={2018-01-01=2018-01-07}}
        Map<Integer, Map<Date, Date>> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN);
        Date parse = format.parse(monthDay);
        //设置为这个月的第一天
        Date date = org.apache.commons.lang3.time.DateUtils.setDays(parse, 1);

        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        calendar.setTime(date);
        //获取这个月有多少天
        int lastDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        //获取这个月第一天对应的dayOfWeek
        int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        //如果是0为周日
        if (firstDayOfWeek == 0) {
            firstDayOfWeek = 7;
        }
        //如果第一天为周一则顺延
        if (firstDayOfWeek == 1) {
            //获取这个月的整周数
            int n = lastDayOfMonth / 7;
            for (int i = 1; i <= n; i++) {
                Map<Date, Date> dateMap = new HashMap<>();
                if (i != 1) {
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                }
                Date date1 = calendar.getTime();
                calendar.add(Calendar.DAY_OF_MONTH, 6);
                Date date2 = calendar.getTime();
                dateMap.put(date1, date2);
                map.put(i, dateMap);
            }
            return map;
        }
        //如果不为周一,取上个月最后几天补全
        int needed = firstDayOfWeek - 1;
        calendar.add(Calendar.DAY_OF_MONTH, -needed);
        //获取第一周首尾日期
        Date head = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, +6);
        Date end = calendar.getTime();
        Map<Date, Date> first = new HashMap<>();
        first.put(head, end);
        map.put(1, first);
        //求出这个月剩余的天数有几整周
        int days = lastDayOfMonth - calendar.get(Calendar.DAY_OF_MONTH);
        int n = days / 7;
        for (int i = 2; i <= (n + 1); i++) {
            Map<Date, Date> dateMap = new HashMap<>();
            calendar.add(Calendar.DAY_OF_MONTH, +1);
            Date date1 = calendar.getTime();
            calendar.add(Calendar.DAY_OF_MONTH, +6);
            Date date2 = calendar.getTime();
            dateMap.put(date1, date2);
            map.put(i, dateMap);
        }
        return map;
    }

    /**
     * 获取某月的第一天和最后一天
     * @param dateTime yyyy-MM-dd or yyyy-MM-dd HH:mm:ss
     * @return key-这个月第一天 value-这个月最后一天
     */
    public static Map<Date, Date> getFirstLast(String dateTime) {
        if (StringUtils.isEmpty(dateTime)) {
            return null;
        }
        SimpleDateFormat formatDate = new SimpleDateFormat(DATE_PATTERN);
        SimpleDateFormat formatDateTime = new SimpleDateFormat(DATE_TIME_PATTERN);
        Date date = null;
        try {
            date = formatDate.parse(dateTime);
        } catch (ParseException e) {
            try {
                date = formatDateTime.parse(dateTime);
            } catch (ParseException e1) {
                throw new RuntimeException(e1.getMessage());
            }
        }
        //获取这个月第一天
        Date first = org.apache.commons.lang3.time.DateUtils.setDays(date, 1);
        //获取最后一天
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        calendar.setTime(first);
        int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.add(Calendar.DAY_OF_MONTH, lastDay - 1);
        Date last = calendar.getTime();
        Map<Date, Date> map = new HashMap<>();
        map.put(first, last);
        return map;
    }


    public static void main(String[] args) throws Exception {
        getFirstLast("2018-02-12 12:12:43");
    }

    /**
     * 获取两个日期之间的日期
     * @param startStr
     * @param endStr
     * @return
     */
    public static List<Date> getBetweenDateStr(String startStr, String endStr) {
        try {
            Date start = DateUtils.stringToDate(startStr);
            Date end = DateUtils.stringToDate(endStr);
            List<Date> result = new ArrayList<Date>();
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            tempStart.add(Calendar.DAY_OF_YEAR, 1);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            while (tempStart.before(tempEnd)) {
                result.add(tempStart.getTime());
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
            return result;
        }catch (Exception e){
            e.getMessage();
        }
        return null;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_31150365/article/details/85250967