public class DateUtils
{
        public static final String                            SHORT_DATE             = "yyyy-MM-dd";
        public static final String                            SHORT_DATE_US  = "yyyy-MM-dd";
        public static final String                            LONG_DATE              = "yyyy-MM-dd HH:mm:ss";
        public static final String                            YMDHM                  = "yyyy-MM-dd HH:mm";
        public static final String                            HM                             = "HH:mm";
        public static final SimpleDateFormat  DF_SHORT_CN            = new SimpleDateFormat(SHORT_DATE);
        public static final SimpleDateFormat  SDF_YMDHM              = new SimpleDateFormat(YMDHM);
        public static final SimpleDateFormat  SDF_HM                 = new SimpleDateFormat(HM);
        public static final SimpleDateFormat  DF_CN                  = new SimpleDateFormat(LONG_DATE);
        public static final int                                      REALTIME               = 0;
 
        public static final int                                      HOURLY                 = 1;
        public static final int                                      DAILY                  = 2;
        public static final int                                      BIWEEKLY               = 3;
        public static final int                                      WEEKLY                 = 4;
        public static final int                                      MONTHLY                = 5;
        public static final int                                      QUARTLY                = 6;
        public static final int                                      BIYEARLY               = 7;
        public static final int                                      YEARLY                 = 8;
 
        public static final long                              day                            = 86400000l;
 
        private DateUtils()
        {
        }
 
        /**
         * Calendar -> String
         */
        public static String format(Calendar cal)
        {
               return format(cal.getTime());
        }
 
        /**
         * Calendar,String -> String
         */
        public static String format(Calendar cal, String pattern)
        {
               return format(cal.getTime(), pattern);
        }
 
        /**
         * Calendar,DateFormat -> String
         */
        public static String format(Calendar cal, DateFormat df)
        {
               return format(cal.getTime(), df);
        }
 
        /**
         * Date -> String
         */
        public static String format(Date date)
        {
               return format(date, DF_CN);
        }
 
        /**
         * Date,String -> String
         */
        public static String format(Date date, String pattern)
        {
               SimpleDateFormat df = new SimpleDateFormat(pattern);
               return format(date, df);
        }
 
        public static String format(long ts, DateFormat df)
        {
               return format(new Date(ts), df);
        }
        
        public static String format(long ts, String format,Locale local)
        {
               SimpleDateFormat df = new SimpleDateFormat(format, local);
               return format(new Date(ts), df);
        }
 
        /**
         * Date,DateFormat -> String
         */
        public static String format(Date date, DateFormat df)
        {
//             if (date == null)
//                     return "";
//
//             if (df != null)
//             {
//                     return df.format(date);
//             }
//             return DF_CN.format(date);
               if(date==null)return "";
               return getRealDateFormat(df).format(date);
        }
 
        public static long getGapMin(long minsec)
        {
               return minsec / 60000;
        }
 
        public static long getGapMinByAddtime(long addtime)
        {
               return getGapMinByAddtime(addtime, System.currentTimeMillis());
        }
 
        public static long getGapMinByAddtime(long addtime, long current)
        {
               return getGapMin(current - addtime);
        }
 
        public static String getGapMinStirngByAddtime(long addtime, long current)
        {
               return getMinStirngBySubTime(getGapMin(current - addtime));
        }
 
        public static String getMinStirngBySubTime(long min)
        {
               long hour = min / 60;
               long restmin = min % 60;
               return (hour > 0 ? hour + "时" : "") + restmin + "分";
        }
 
        public static Calendar parseDateString(String str, String format)
        {
               if (str == null)
               {
                       return null;
               }
               Date date = null;
               SimpleDateFormat df = new SimpleDateFormat(format);
               try
               {
                       date = getRealDateFormat(df).parse(str);
               }
               catch (Exception ex)
               {
 
               }
               if (date == null)
               {
                       return null;
               }
               Calendar cal = Calendar.getInstance();
               cal.setTime(date);
               return cal;
        }
 
        /**
         * returns the current date in the default format
         */
        public static String getToday()
        {
               return format(new Date());
        }
 
        public static Date getYesterday()
        {
               Calendar cal = Calendar.getInstance();
               cal.add(Calendar.DATE, -1);
 
               return cal.getTime();
        }
 
        public static Calendar getFirstDayOfMonth()
        {
               Calendar cal = getNow();
               cal.set(Calendar.DAY_OF_MONTH, 1);
               cal.set(Calendar.HOUR_OF_DAY, 0);
               cal.set(Calendar.MINUTE, 0);
               cal.set(Calendar.SECOND, 0);
 
               return cal;
        }
        /**
         * 获取某月的第一天
         * @param month
         * @return Calendar
         * */
        public static Calendar getFirstDayOfMonth(int month)
        {
               Calendar cal = Calendar.getInstance();
               cal.set(Calendar.MONTH, month);
               cal.set(Calendar.DAY_OF_MONTH, 1);
               cal.set(Calendar.HOUR_OF_DAY, 0);
               cal.set(Calendar.MINUTE, 0);
               cal.set(Calendar.SECOND, 0);
 
               return cal;
        }
 
        public static Calendar getNow()
        {
               return Calendar.getInstance();
        }
 
        /**
         * add some month from the date
         */
        public static Date addMonth(Date date, int n) throws Exception
        {
               Calendar cal = getNow();
               cal.setTime(date);
               cal.add(Calendar.MONTH, n);
               return cal.getTime();
        }
 
        public static int daysBetween(Date returnDate)
        {
               return daysBetween(null, returnDate);
        }
 
        public static long tirmDay(Calendar time)
        {// 得到当天的0点时间
               time.set(Calendar.HOUR_OF_DAY, 0);
               time.set(Calendar.MINUTE, 0);
               time.set(Calendar.SECOND, 0);
               time.set(Calendar.MILLISECOND, 0);
               return time.getTimeInMillis();
        }
 
        public static int daysBetween(Date now, Date returnDate)
        {
               if (returnDate == null)
                       return 0;
 
               Calendar cNow = getNow();
               Calendar cReturnDate = getNow();
               if (now != null)
               {
                       cNow.setTime(now);
               }
               cReturnDate.setTime(returnDate);
               setTimeToMidnight(cNow);
               setTimeToMidnight(cReturnDate);
               long nowMs = cNow.getTimeInMillis();
               long returnMs = cReturnDate.getTimeInMillis();
               return millisecondsToDays(nowMs - returnMs);
        }
 
        private static int millisecondsToDays(long intervalMs)
        {
               return (int) (intervalMs / (1000 * 86400));
        }
 
        private static void setTimeToMidnight(Calendar calendar)
        {
               calendar.set(Calendar.HOUR_OF_DAY, 0);
               calendar.set(Calendar.MINUTE, 0);
               calendar.set(Calendar.SECOND, 0);
        }
 
        public static String formatDate(Object obj, String format)
        {
               String result = "";
               try
               {
                       Date date = (Date) obj;
                       result = format(date, format);
               }
               catch (Exception e)
               {
 
               }
               return result;
        }
 
        public static String formatDate(Object obj)
        {
               return formatDate(obj, SHORT_DATE);
        }
 
        public static String getSunday(String date)
        {
               Calendar c = DateUtils.parseDateString(date, "yyyy-MM-dd");
               int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
               if (dayofweek == 0)
               {
                       dayofweek = 0;
               }
               c.add(Calendar.DATE, -dayofweek);
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
               return sdf.format(c.getTime());
        }
 
        public static Calendar getStartTime(Calendar calendar, int interval)
        {
               if (calendar == null)
                       return null;
               Calendar fromtime = Calendar.getInstance();
               fromtime.setTimeZone(calendar.getTimeZone());
               fromtime.set(Calendar.MILLISECOND, 0);
               int y = calendar.get(Calendar.YEAR);
               int m = calendar.get(Calendar.MONTH);
               int d = calendar.get(Calendar.DAY_OF_MONTH);
               if (interval == DAILY || interval == HOURLY)
               {
                       fromtime.set(y, m, d, 0, 0, 0);
               }
               else if (interval == WEEKLY)
               {
                       fromtime.set(y, m, d, 0, 0, 0);
                       fromtime.add(Calendar.DATE, 1 + Calendar.SUNDAY - fromtime.get(Calendar.DAY_OF_WEEK));
               }
               else if (interval == MONTHLY)
               {
                       fromtime.set(y, m, 1, 0, 0, 0);
               }
               else if (interval == BIWEEKLY)
               {
                       fromtime.set(y, m, d, 0, 0, 0);
                       fromtime.add(Calendar.WEEK_OF_YEAR, (-1) * (fromtime.get(Calendar.WEEK_OF_YEAR) + 1) % 2);
                       fromtime.add(Calendar.DATE, Calendar.SUNDAY - fromtime.get(Calendar.DAY_OF_WEEK));
               }
               else if (interval == YEARLY)
               {
                       fromtime.set(y, m, d, 0, 0, 0);
               }
               else if (interval == QUARTLY)
               {
                       fromtime.set(y, (m / 3) * 3, 1, 0, 0, 0);
               }
               else if (interval == BIYEARLY)
               {
                       fromtime.set(y, (m / 6) * 6, 1, 0, 0, 0);
               }
               return fromtime;
        }
 
        public static Calendar getEndTime(Calendar calendar, int interval)
        {
               if (calendar == null)
                       return null;
               Calendar endtime = Calendar.getInstance();
               endtime.setTimeZone(calendar.getTimeZone());
               endtime.set(Calendar.MILLISECOND, 0);
               int y = calendar.get(Calendar.YEAR);
               int m = calendar.get(Calendar.MONTH);
               int d = calendar.get(Calendar.DAY_OF_MONTH);
               if (interval == DAILY)
               {
                       endtime.set(y, m, d, 0, 0, 0);
                       endtime.add(Calendar.DAY_OF_MONTH, 1);
               }
               else if (interval == WEEKLY)
               {
                       endtime.set(y, m, d, 0, 0, 0);
                       endtime.add(Calendar.DATE, 2 + Calendar.SATURDAY - endtime.get(Calendar.DAY_OF_WEEK));
               }
               else if (interval == MONTHLY)
               {
                       endtime.set(y, m, 1, 0, 0, 0);
                       endtime.add(Calendar.MONTH, 1);
               }
               else if (interval == BIWEEKLY)
               {
                       endtime.set(y, m, d, 0, 0, 0);
                       endtime.add(Calendar.WEEK_OF_YEAR, endtime.get(Calendar.WEEK_OF_YEAR) % 2);
                       endtime.add(Calendar.DATE, 1 + Calendar.SATURDAY - endtime.get(Calendar.DAY_OF_WEEK));
               }
               else if (interval == YEARLY)
               {
                       endtime.set(y + 1, m, d, 0, 0, 0);
               }
               else if (interval == QUARTLY)
               {
                       if (m / 3 == 3)
                       {
                               endtime.set(y + 1, 0, 1, 0, 0, 0);
                       }
                       else
                       {
                               endtime.set(y, (m / 3 + 1) * 3, 1, 0, 0, 0);
                       }
               }
               else if (interval == BIYEARLY)
               {
                       if (m / 6 == 1)
                       {
                               endtime.set(y + 1, 0, 1, 0, 0, 0);
                       }
                       else
                       {
                               endtime.set(y, (m / 6 + 1) * 6, 1, 0, 0, 0);
                       }
               }
               return endtime;
        }
 
        public static long getDays(String startdate, String enddate, String format)
        {
               Calendar s1 = DateUtils.parseDateString(startdate, format);
               Calendar s2 = DateUtils.parseDateString(enddate, format);
               if (s1 != null && s2 != null)
               {
                       return getDays(s1.getTimeInMillis(), s2.getTimeInMillis());
               }
               return 0;
        }
 
        public static long getMonthDays(String date, String format)
        {
               Calendar cal = DateUtils.parseDateString(date, format);
               if (cal != null)
               {
                       Calendar starttime = DateUtils.getStartTime(cal, DateUtils.MONTHLY);
                       Calendar endtime = DateUtils.getEndTime(cal, DateUtils.MONTHLY);
                       return getDays(starttime.getTimeInMillis(), endtime.getTimeInMillis());
               }
               return 0;
        }
 
        public static long getDays(long startdate, long enddate)
        {
               return (enddate - startdate) / day;
        }
 
        public static String format(Long l, String pattern)
        {
               if(l==null)return "";
               Calendar cal = Calendar.getInstance();
               cal.setTimeInMillis(l);
               return format(cal.getTime(), pattern);
        }
        
        public static DateFormat getRealDateFormat(DateFormat df)
        {
               return df==null?new SimpleDateFormat(SHORT_DATE_US,Locale.US):df;
        }
 
        //smdate="2004-03-26 13:31:40"
        //bdate="2004-03-26 11:30:24
    public static String daysBetween(String smdate,String bdate,String formate) throws ParseException
    {
        SimpleDateFormat df = new SimpleDateFormat(formate);
               Date now=null;
               Date date=null;
               String result="";
               try {
                       now = df.parse(smdate);
                       date = df.parse(bdate);
                        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);
                        //System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");
                        result= day==0?"":day+"天";
                        result+=hour==0?"":hour+"小时";
                        result+=min==0?"":min+"分";
                        result+=s==0?"":s+"秒";
               } catch (ParseException e) {
                       // TODO Auto-generated catch block
                       result="";
               }
               return result;
    }  
    
    /**
     * 获取当前月与之前的N-1个月份
     * @param n 获取月份数
     * @return 'yyyy-MM'
     * */
    public static List<String> getCurrentMonths(int n){
               List<String> months=new ArrayList<String>();
               for(int i=n-1;i>=0;i--){
                       Calendar cal = Calendar.getInstance();
                       cal.add(Calendar.MONTH,i-n+1);
                   int month = cal.get(Calendar.MONTH) + 1;
                   int year = cal.get(Calendar.YEAR);
                   months.add(year+""+(month<10?"0"+month:""+month));
               }
               return months;
        }
    /**
     * 获取某年最后一天
     * @param year int
     * @return Date
     * */
    public static Date getCurrYearLast(int year){
               Calendar calendar = Calendar.getInstance();
               calendar.clear();
               calendar.set(Calendar.YEAR, year);
               calendar.roll(Calendar.DAY_OF_YEAR, -1);
               Date currYearLast = calendar.getTime();
               
               return currYearLast;
        }    
}

时间处理工具类DateUtils的更多相关文章

  1. java时间处理工具类--DateUtils

    package com.hexiang.utils; /** * @(#)DateUtil.java * * * @author kidd * @version 1.00 2007/8/8 */ im ...

  2. java 日期工具类DateUtils

      日期工具类DateUtils CreateTime--2017年5月27日08:48:00Author:Marydon DateUtils.java-对日期类的进一步封装 import java. ...

  3. [java工具类01]__构建格式化输出日期和时间的工具类

    在之前的学习中,我写过一篇关于字符串格式化的,就主要设计到了时间以及日期的各种格式化显示的设置,其主要时通过String类的fomat()方法实现的. 我们可以通过使用不同的转换符来实现格式化显示不同 ...

  4. Java中Date类型如何向前向后滚动时间,( 附工具类)

    Java中的Date类型向前向后滚动时间(附工具类) 废话不多说,先看工具类: import java.text.SimpleDateFormat; import java.util.Calendar ...

  5. Java日期时间实用工具类

    Java日期时间实用工具类 1.Date (java.util.Date)    Date();        以当前时间构造一个Date对象    Date(long);        构造函数   ...

  6. jdk8 时间日期工具类(转)

    package com.changfu.common.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jav ...

  7. JAVA 日期处理工具类 DateUtils

    package com.genlot.common.utils; import java.sql.Timestamp;import java.text.ParseException;import ja ...

  8. Android经常使用工具类DateUtils(二)

    在编写代码中,会经经常使用到时间Date这个类,小编整理了一些经常使用的时间工具类.供大家參考. import java.text.ParseException; import java.text.S ...

  9. 日期工具类 DateUtils(继承org.apache.commons.lang.time.DateUtils类)

    /** * */ package com.dsj.gdbd.utils.web; import org.apache.commons.lang3.time.DateFormatUtils; impor ...

随机推荐

  1. oracle大数据量。表分区提示查询效率

    现在业务有一张usertrack 日志记录表.每天会产生30万条数据.数据量大查询效率会非常慢 所以我考虑通过表分区来提示效率  逻辑上是一张表.但是分区后会按照分区条件将数据分在不同的物理文件 优点 ...

  2. Linux修改密码passwd用法

    语法: passwd [-k] [-l] [-u [-f]] [-d] [-S] [username] 必要参数:-d 删除密码-f 强制执行-k 更新只能发送在过期之后-l 停止账号使用-S 显示密 ...

  3. Jenkins配置MSBuild时使用环境变量

    [MSBuild Plugin]插件在使用环境变量有个很奇葩的方式,比如我们通常在Windows的节点机器上,使用WORKSPACE环境变量时,批处理应该这样写%WORKSPACE%,而有时插件确不能 ...

  4. System.BadImageFormatException: 未能加载文件或程序集""或它的某一个依赖项。试图加载格式不正确的程序。

    解决方法: 1.更改程序集的生成目标平台为[Any CPU],或者针对平台进行编译. 项目右键->[属性]->[生成]->[生成目标平台] 2.尝试一下修改线程池设置为32位支持.

  5. linux最常用的20条命令

    玩过Linux的人都会知道,Linux中的命令的确是非常多,但是玩过Linux的人也从来不会因为Linux的命令如此之多而烦恼,因为我们只需要掌握我们最常用的命令就可以了.当然你也可以在使用时去找一下 ...

  6. MVC5-1 ASP.NET的管道流

    MVC5 和WebForm的区别 WebForm是一个Page贯穿了一个.CS代码. 1对1 = 耦合在一起 MVC在Controller中将 bihind和page进行了分离. 多对多 = 松耦合 ...

  7. 解析:使用easyui的form提交表单,在IE下出现类似附件下载时提示是否保存的现象

    之前开发时遇到的一个问题,使用easyui的form提交表单,在Chrome下时没问题的,但是在IE下出现类似附件下载时提示是否保存的现象. 这里记录一下如何解决的.其实这个现象不光是easyui的f ...

  8. 【Beta】Daily Scrum 第一天

    [目录] 1.任务进度 2.困难及解决 3.燃尽图 4.代码check-in 5.总结 1. 任务进度 学号 已完成 接下来要完成的 612 添加计时界面返回按键事件,添加SharePreferenc ...

  9. mybatis int 类型判断<if>

    如果数据类型是integer或者int,也就是数据类型的,在用<if>标签做动态语句的时候 不用判断是否为"''" <if test="sex != n ...

  10. Ubuntu 12.04 root账户开启及密码重设

    以普通用户登录,root账号的开启.关闭和密码设置,命令如下: sudo passwd -u root # 启用root账户 sudo passwd root # 设置root 密码(包括重设) su ...