• 时间处理工具类


    import java.sql.Timestamp;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.Iterator;
    import java.util.List;

    import javax.xml.datatype.XMLGregorianCalendar;

    public class DateUtils extends org.apache.commons.lang.time.DateUtils
    {

        public DateUtils()
        {
        }
        //获取当前时间Date类型
        public static Date currentDate()
        {
            return new Date();
        }
        //获取当前时间String类型
        public static String currentString()
        {
            return format(currentDate());
        }
        //获取当前时间的日历类
        public static Calendar getCalendar()
        {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            return calendar;
        }
        //Date类型的时间转换成日历类
        public static Calendar getCalendar(Date date)
        {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar;
        }
        //自 1970.1.1 00:00:00 GMT  +毫秒数=新的日历
        //同方法getMany中②③
        public static Calendar getCalendar(long millis)
        {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(millis);
            return calendar;
        }
        //java.sql.Date类型的时间转换成日历类
        public static Calendar getCalendar(java.sql.Date date)
        {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(date.getTime());
            return calendar;
        }
        /**
         * 时间戳转换成日历
         * @param date
         * @return
         */
        public static Calendar getCalendar(Timestamp date)
        {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(date.getTime());
            return calendar;
        }
        //获得该日历所属的星期:WEEK[1]:星期一,WEEK[2]:星期二,依此类推
        public static String getWeek(Calendar calendar)
        {
            return WEEK[calendar.get(7) - 1];//calendar.get(7)所属一周中的第几天:周末为1;周一为2,以此类推
        }
        //格式转换Date——String(yyyy-MM-dd HH:mm:ss)
        public static String format(Date date)
        {
            return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(date);
        }
        //按指定格式获取当前日期:String类型
        public static String format(String pattern)
        {
            return (new SimpleDateFormat(pattern)).format(currentDate());
        }
        //把日期类型的时间转换成指定格式的String类型
        public static String format(String pattern, Date date)
        {
            return (new SimpleDateFormat(pattern)).format(date);
        }
        //把sql日期类型的时间转换成指定格式的String类型
        public static String format(String pattern, java.sql.Date date)
        {
            return (new SimpleDateFormat(pattern)).format(new Date(date.getTime()));
        }
        //把时间戳类型的时间转换成指定格式的String类型
        public static String format(String pattern, Timestamp date)
        {
            return (new SimpleDateFormat(pattern)).format(new Date(date.getTime()));
        }
        //
        public static String format(String request, String date, String result)
            throws ParseException
        {
            return format(result, parse(request, date));
        }
        //把String类型的时间准换成Date类型
        public static Date parse(String date)
            throws ParseException
        {
            return parseDate(date, patterns);
        }
        //把String类型的时间转换成指定格式的Date类型
        public static Date parse(String pattern, String date)
            throws ParseException
        {
            return (new SimpleDateFormat(pattern)).parse(date);
        }
        //date类型的时间+时+分+秒
        public static Date parse(Date date, int hour, int minute, int second, int millis)
        {
            Calendar retval = getCalendar(date);
            retval.set(11, hour);
            retval.set(12, minute);
            retval.set(13, second);
            retval.set(14, millis);
            return retval.getTime();
        }
        //String类型的时间+时+分+秒:显示为制定格式的Date类型的时间
        public static Date parse(String date, String pattern, int hour, int minute, int second, int millis)
            throws ParseException
        {
            Calendar retval = getCalendar(parse(pattern, date));
            retval.set(11, hour);
            retval.set(12, minute);
            retval.set(13, second);
            retval.set(14, millis);
            return retval.getTime();
        }
        //给指定的时间加上或减去某时间:(amount)指定量,给定日历字段(field),
        public static Date add(Date date, int field, int amount)
        {
            return add(getCalendar(date), field, amount).getTime();
        }
        //给指定的日历加上或减去某时间:(amount)指定量,给定日历字段(field),基于日历的规则。
        public static Calendar add(Calendar date, int field, int amount)
        {
    //     Calendar cal = Calendar.getInstance();
    //     // print current date:The current date is : Thu Apr 26 02:13:28 EEST 2012
    //     System.out.println("The current date is : " + cal.getTime());
    //     // add 20 days to the calendar:20 days later: Wed May 16 02:13:28 EEST 2012
    //     cal.add(Calendar.DATE, 20);
    //     System.out.println("20 days later: " + cal.getTime());
    //     // subtract 2 months from the calendar:2 months ago: Fri Mar 16 02:13:28 EET 2012
    //     cal.add(Calendar.MONTH, -2);
    //     System.out.println("2 months ago: " + cal.getTime());
    //     // subtract 5 year from the calendar:5 years ago: Fri Mar 16 02:13:28 EET 2007
    //     cal.add(Calendar.YEAR, -5);
    //     System.out.println("5 years ago: " + cal.getTime());

         //field -- 日历字段。amount --要添加到该字段的日期或时间的量。
            date.add(field, amount);
            return date;
        }
        //XMLGregorianCalendar转换成Date类型
        public static Date convert(XMLGregorianCalendar calendar)
        {
            GregorianCalendar retval = calendar.toGregorianCalendar();
            return retval.getTime();
        }
        //Calendar转换成Date类型
        public static Date convert(Calendar calendar)
        {
            return calendar.getTime();
        }
        //Timestamp类型转换成Date类型
        public static Date convert(Timestamp timestamp)
        {
            return new Date(timestamp.getTime());
        }
        //java.sql.Date转换成Date类型
        public static Date convert(java.sql.Date date)
        {
            return new Date(date.getTime());
        }
        //毫秒转换成Date类型
        public static Date convert(String millisecond)
        {
            return new Date(Long.valueOf(millisecond).longValue());
        }
        //判断日历是否是周末
        public static Boolean isWeekend(Calendar calendar)
        {
         /**
          * 跟进去的源码:
          * public final static int DAY_OF_WEEK = 7;所以get(7)是得到当天属于一周的第几天,默认周末返回1,周一返回2
          * Field number for <code>get</code> and <code>set</code> indicating the day
             * of the week.  This field takes values <code>SUNDAY</code>,
             * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
             * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
             **/
         //同理:cal.get(1):得到的是现在是哪一年;cal.get(2):得到的是现在月份的前一个月;cal.get(5):得到的是现在的那一天;cal.get(6):属于一年中的第几天等等
         //java.util.Calendar.get(int field) 方法返回给定日历字段的值。field -- 给定日历字段:Calendar.YEAR/MONTH/DATE:年/前一个月份/日
         //异常:ArrayIndexOutOfBoundsException - 如果指定的字段超出范围
            int day = calendar.get(7);
            if(day != 1 && day != 7)//1为周末,7为周六
                return Boolean.valueOf(false);
            else
                return Boolean.valueOf(true);
        }
        //判断date类型的时间是否是周末:先转换成日历格式,再判断
        public static Boolean isWeekend(Date date)
        {
            return isWeekend(getCalendar(date));
        }
        //判断java.sql.Date类型的时间是否是周末:先转换成日历格式,再判断
        public static Boolean isWeekend(java.sql.Date date)
        {
            return isWeekend(getCalendar(date));
        }
        ////判断Timestamp类型的时间是否是周末:先转换成日历格式,再判断
        public static Boolean isWeekend(Timestamp date)
        {
            return isWeekend(getCalendar(date));
        }
        //计算两个日历之前的天数
        public static int betweenDays(Calendar start, Calendar end)
        {
            if(start == null || end == null || start.after(end))
                return -1;
            /**public final static int DAY_OF_YEAR = 6;Calendar.get(6):得到该时间属于一年当中第几天
             * Field number for <code>get</code> and <code>set</code> indicating the day
             * number within the current year.  The first day of the year has value 1.
             */
            int days = end.get(6) - start.get(6);
           
            if(start.get(1) != end.get(1))//判断若不属于同一年份
            {
                start = (Calendar)start.clone();
                do
                {
                    days += start.getActualMaximum(6);//查询当前天数(年、月、周)拥有的最大值。
                    start = add(start, 1, 1);//每次加一年
                } while(start.get(1) != end.get(1));//当start.get(1) = end.get(1)时,结束循环
            }
            return days;
        }
        //计算两个日历之间的天数
        public static int betweenWorkDays(Calendar start, Calendar end)
        {
            return betweenWorkDays(start, end, null, null);
        }
        //计算两个日历之间的工作日天数
        public static int betweenWorkDays(Calendar start, Calendar end, List workday, List restday)
        {
            if(start == null || end == null || start.after(end))
                return -1;
            //如果是周六日,直接返回0,否则返回7-该日历属于一周中第几天(周日属于第一天,周一属于第二天)
            int _start_displace = isWeekend(start).booleanValue() ? 0 : 7 - start.get(7);
            //如果是周六日,直接返回0,否则返回7-一周中第几天-1(周日属于第一天,周一属于第二天)
            int _end_displace = isWeekend(end).booleanValue() ? 0 : 7 - end.get(7) - 1;//
            //(起始日历的下个周一 和 结束日历的下个周一   之间的天数)/7*5+_start_displace-_end_displace
            int days = ((betweenDays(getNextMonday(start), getNextMonday(end)) / 7) * 5 + _start_displace) - _end_displace;
            if(workday != null && !workday.isEmpty())
                days += betweenHolidayDays(start, end, workday);
            if(restday != null && !restday.isEmpty())
                days -= betweenHolidayDays(start, end, restday);
            return days;
        }
        //计算两个日历之间的时间在holidays列表中存在的的假期天数
        public static int betweenHolidayDays(Calendar start, Calendar end, List holidays)
        {
            int retval = 0;
            for(Iterator iterator = holidays.iterator(); iterator.hasNext();)
            {
                Date date = (Date)iterator.next();
                Calendar temp = getCalendar(date);
                if((temp.after(start) || temp.compareTo(start) == 0) && (end.after(temp) || end.compareTo(temp) == 0))
                    retval++;
            }

            return retval;
        }
        //获取该日期的下个周一的日历
        public static Calendar getNextMonday(Calendar date)
        {
            date = (Calendar)date.clone();
            do
                date = add(date, 5, 1);//每次加一天
            while(date.get(7) != 2);//当该日期不是周一的时候一直循环
            return date;
        }
        //获取输入日期所属那周的周一的日期
        public static Date getMonday(Date date)
        {
            Calendar day = Calendar.getInstance();
            day.setTime(date);
            day.set(7, 2);
            return day.getTime();
        }
        //获取某日期所属那周的周末的日期
        public static Date getSunday(Date date)
        {
            Calendar day = Calendar.getInstance();
            day.setTime(date);
            if(7 == day.getFirstDayOfWeek())
            {
                return date;
            } else
            {
                day.add(6, 7);
                day.set(7, 1);//{设置周(7)为所属那周的第一天:周末
                return day.getTime();
            }
        }
        //获取当前日期所属月份的第一天的日期
        public static Date getMonthFirstDay()
        {
            Calendar calendar = Calendar.getInstance();
            calendar.set(5, calendar.getActualMinimum(5));
            return calendar.getTime();
        }
        //获取当前日期所属月份的最后一天的日期
        public static Date getMonthLastDay()
        {
            Calendar calendar = Calendar.getInstance();
            calendar.set(5, calendar.getActualMaximum(5));
            return calendar.getTime();
        }

        public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
        public static final String DAY_PATTERN = "yyyy-MM-dd";
        //因为编码问题,ISO-8859-1(国际通用编码),中文会显示为"u65E5"的字符
        public static final String WEEK[] = {
            "u65E5", "u4E00", "u4E8C", "u4E09", "u56DB", "u4E94", "u516D"
        };
        public static final String patterns[] = {
            "EEE MMM dd HH:mm:ss zzz yyyy", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH", "yyyy-MM-dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM/dd HH", "yyyy/MM/dd", "yyyyMMddHHmmss",
            "yyyyMMddHHmm", "yyyyMMddHH", "yyyyMMdd", "MM/dd/yyyy HH:mm:ss", "MM/dd/yyyy HH:mm", "MM/dd/yyyy HH", "MM/dd/yyyy", "yyyyMM", "yyyy", "yyyy|MM|dd"
        };
       
       
       
       
        //①获取当前系统时间的毫秒数②自 1970.1.1 00:00:00 GMT +固定毫秒数=某时间③自 1970.1.1 00:00:00 GMT +当前系统的毫秒数=当前时间
        public static int getMany(){
         Date curDate = new Date();//当前时间
         //①获得当前系统时间的毫秒数,自 1970.1.1 00:00:00 GMT   
         long time = System.currentTimeMillis();
         //②自 1970.1.1 00:00:00 GMT +固定毫秒数=某时间
         Date date1 = new Date(Long.valueOf("1503977532450").longValue());
         //③自 1970.1.1 00:00:00 GMT +当前系统的毫秒数=当前时间
         Date date2 = new Date(time);
         System.out.println("curDate = " + curDate.toString());//curDate = Tue Aug 29 11:54:22 CST 2017
         System.out.println("millisecond = " + time);//millisecond = 1503978862497
         System.out.println("date1 = " + date1.toString());//date1 = Tue Aug 29 11:32:12 CST 2017
         System.out.println("date2 = " + date2.toString());//date2 = Tue Aug 29 11:54:22 CST 2017
         return (int) time;
        }
       
        /**
         * Java 日历类 Calendar 相关方法
         * ************************************************************************************************
         * ************************************************************************************************
         * ************************************************************************************************
         * ************************************************************************************************
         */
        /**
         * 计算指定日期为当年第几周
         * @param year  指定的年份
         * @param month  指定的月份
         * @param day  指定的日
         * @return   指定日期为当年的第几周
         */
        public static int caculateWeekOfYear(int year,int month,int day){
         Calendar c = Calendar.getInstance();
         c.set(Calendar.YEAR, year);
         c.set(Calendar.MONTH, month - 1);
         c.set(Calendar.DATE, day);
         return c.get(Calendar.WEEK_OF_YEAR);
        }
       
        /**
         * 获取本月第一天是星期几
         * @return
         */
        public static int getWeekOfFirstDay(Calendar c){
         Calendar calendar = c;
         calendar.set(Calendar.DAY_OF_MONTH, 1);//本月第一天set进去
         /*
          * this field takes values <code>SUNDAY</code>,   ---返回1
          * <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>, ---返回2,3,4
          * <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code> ---返回5,6,7
          */
         return calendar.get(Calendar.DAY_OF_WEEK);
        }
       
        /**
         * 获取本月1号是该年的第几周
         * @return
         */
        public static int getMonthStartWeek(Calendar c){
         Calendar calendar = c;
         calendar.set(Calendar.DATE, 1);
         return calendar.get(Calendar.WEEK_OF_YEAR);
        }
       
        /**
         * 获取当天是该年的第几周
         */
        public static int getCurrentWeekOfYear(){
         Calendar calendar = Calendar.getInstance();
         return calendar.get(Calendar.WEEK_OF_YEAR);
        }
       
        /**
         * 获取上月的总天数
         * @return
         */
        public static int getLastMonthDays(Calendar c){
         Calendar calendar = c;
         calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
         return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
       
        /**
         * 获取指定月份的总天数
         * @return
         */
        public static int getCurrentMonthDays(int month){
         Calendar c = Calendar.getInstance();
         c.set(Calendar.MONTH, month);
         return c.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
       
        /**
         * 获取指定年份有多少周
         * @param year
         * @return
         */
        public static int getTotalWeekOfYear(int year){
         Calendar c = Calendar.getInstance();
         return c.getActualMaximum(Calendar.WEEK_OF_YEAR);
        }
       
        /**
         * 判断指定月份是否是当前月
         * @param month
         * @return
         */
        public static boolean isCurrentMonth(int month){
      Calendar c = Calendar.getInstance();
      return (c.get(Calendar.MONTH) == month)?true:false;
     }
       
        /**
         * 计算指定的月份共有多少天
         */
        public static int getTotalDaysOfMonth(int year, int month){
         Calendar c = Calendar.getInstance();
      c.set(Calendar.YEAR, year);
      c.set(Calendar.MONTH, month);
      c.set(Calendar.DATE, 1);
      /**
       * 计算这个月有多少天
       */
      return c.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
       

    }

  • 相关阅读:
    (.*?)懒惰正则
    re.S
    import和from import陷阱一
    import和from import陷阱二
    Linux中查看文件编码
    环境部署策略
    简便删除已经存在的oracle数据库用户UPAY3LINGXI_YS
    ssh连接linux服务器只显示-bash-4.1#不显示路径解决方法
    ubuntu安装出现"删除initramfs-tools时出错",subprocess installed post-installation script returned error exit status 1
    python下载链接内容
  • 原文地址:https://www.cnblogs.com/whhjava/p/7452822.html
Copyright © 2020-2023  润新知