Java DateUtil 日期工具类

来源:互联网 发布:软件健壮性 软件可靠性 编辑:程序博客网 时间:2024/06/05 06:50

Java DateUtil 工具类


package com.chinasofti.homework0608;    import java.text.ParseException;    import java.text.SimpleDateFormat;    import java.util.Calendar;    import java.util.Date;    /**     * DateUtil     * @author Administrator     */    public class DateUtil {        public static final String DATE_PATTERN = "yyyy-MM-dd";        /**         * 添加天数         * @return         */        public static Date addDay(Date date, int days) {            Calendar d = Calendar.getInstance();            d.setTime(date);            d.add(Calendar.DAY_OF_MONTH, days);            return d.getTime();        }        /**         * 添加月         * @return         */        public static Date addMouth(Date date, int mouth) {            Calendar m = Calendar.getInstance();            m.setTime(date);            m.add(Calendar.MONTH, mouth);            return m.getTime();        }        /**         * 添加年         * @return         */        public static Date addYear(Date date, int year) {            Calendar y = Calendar.getInstance();            y.setTime(date);            y.add(Calendar.YEAR, year);            return y.getTime();        }        /**         * 日期格式化(自定义格式)         * @param date         * @param format         * @return         */        public static String format(Date date, String format){            SimpleDateFormat sdf = new SimpleDateFormat(format);            return sdf.format(date);        }        /**         * 解析日期(默认日期格式)         * @throws ParseException          *           */        public static Date parse(String string){            SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);            try {                Date d = sdf.parse(string);                return d;            } catch (ParseException e) {                e.printStackTrace();            }            return null;            }        /**         * 解析日期(自定日期格式)         * @throws ParseException          *           */        public static Date parse2(String string,String str){            SimpleDateFormat sdf = new SimpleDateFormat(str);            try {                Date d = sdf.parse(string);                return d;            } catch (ParseException e) {                e.printStackTrace();            }            return null;            }        /**         * 比较日期的先后         *           */         public static Date compare(Date date1,Date date2){            return (date1.compareTo(date2))>0?date1:date2;        }        /**         * 比较日期之间相差的天数         *           */         public static long differ(Date date1,Date date2){        return (date1.getTime()-date2.getTime())/1000/60/60/24;        }}
原创粉丝点击