`

java 时间Utils

 
阅读更多

 基础知识点:

start

  1. 字母 日期或时间元素 表示 示例  
  2. G Era 标志符 Text AD  
  3. y 年 Year 1996; 96  
  4. M 年中的月份 Month July; Jul; 07  
  5. w 年中的周数 Number 27  
  6. W 月份中的周数 Number 2  
  7. D 年中的天数 Number 189  
  8. d 月份中的天数 Number 10  
  9. F 月份中的星期 Number 2  
  10. E 星期中的天数 Text Tuesday; Tue  
  11. a Am/pm 标记 Text PM  
  12. H 一天中的小时数(0-23) Number 0  
  13. k 一天中的小时数(1-24) Number 24  
  14. K am/pm 中的小时数(0-11) Number 0  
  15. h am/pm 中的小时数(1-12) Number 12  
  16. m 小时中的分钟数 Number 30  
  17. s 分钟中的秒数 Number 55  
  18. S 毫秒数 Number 978  
  19. z 时区 General time zone Pacific Standard Time; PST; GMT-08:00  
  20. Z 时区 RFC 822 time zone -0800  
  21.   
  22. 引用  
  23.   
  24. 日期和时间模式 结果  
  25. "yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT  
  26. "EEE, MMM d, ''yy" Wed, Jul 4, '01  
  27. "h:mm a" 12:08 PM  
  28. "hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time  
  29. "K:mm a, z" 0:08 PM, PDT  
  30. "yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM  
  31. "EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700  
  32. "yyMMddHHmmssZ" 010704120856-0700  
  33. "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700 

end

 

 

代码:

package com.miv.core.utils;

 

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;

import java.util.Date;

import java.util.GregorianCalendar;

import java.util.List;

 

import org.apache.commons.lang.StringUtils;

 

public class DateUtils {

    public static class DateBean {

        private Date start;

        private Date end;

 

        public Date getStart() {

            return start;

        }

 

        public void setStart(Date start) {

            this.start = start;

        }

 

        public Date getEnd() {

            return end;

        }

 

        public void setEnd(Date end) {

            this.end = end;

        }

    }

 

    public static final String M_C_PREFIX_YEAR = "20";

    // 年-月-日

    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    // 年-月-日 时:分

    public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

    // 年-月-日 时:分:秒

    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    // 年月日

    public static final String YYYYMMDD = "yyyyMMdd";

    // 年月日 时分

    public static final String YYYYMMDDHHMM = "yyyyMMddHHmm";

    // 年月日 时分秒

    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    // 年月日 时分秒毫秒

    public static final String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmsssss";

    // 年

    public static final String YYYY = "yyyy";

    // 月

    public static final String MM = "MM";

 

    public static final Calendar calendar = Calendar.getInstance();

 

    /**

     * 

     * 功能描述 月份控件

     * 

     * <pre>

     * 特殊说明  使用DateUtils.Month month = DateUtils.Month.JANUARY;

     * month.NAME()

     * </pre>

     * 

     * @author R20962

     * @create Aug 21, 2012

     * 

     */

    public static class Month {

        public static Month NEW_YEAR = null;

        public static Month JANUARY = null;

        public static Month FEBRUARY = null;

        public static Month MARCH = null;

        public static Month APRIL = null;

        public static Month MAY = null;

        public static Month JUNE = null;

        public static Month JULY = null;

        public static Month AUGUST = null;

        public static Month SEPTEMBER = null;

        public static Month OCTOBER = null;

        public static Month NOVEMBER = null;

        public static Month DECEMBER = null;

 

        static {

            NEW_YEAR = new Month("0", "元旦", 0);

            JANUARY = new Month("1", "一月", 1);

            FEBRUARY = new Month("2", "二月", 2);

            MARCH = new Month("3", "三月", 3);

            APRIL = new Month("4", "四月", 4);

            MAY = new Month("5", "五月", 5);

            JUNE = new Month("6", "六月", 6);

            JULY = new Month("7", "七月", 7);

            AUGUST = new Month("8", "八月", 8);

            SEPTEMBER = new Month("9", "九月", 9);

            OCTOBER = new Month("10", "十月", 10);

            NOVEMBER = new Month("11", "十一月", 11);

            DECEMBER = new Month("12", "十二月", 12);

        }

        public static Month[] MONTH = { NEW_YEAR, JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER,

                OCTOBER, NOVEMBER, DECEMBER };

        private Object id; // 匹配 Object.qwuals(month.ID())

        private String name;// 一月 等

        private int arabic;// 数字从1开始

 

        public Month(String id, String name, int arabic) {

            this.id = id;

            this.name = name;

            this.arabic = arabic;

        }

 

        public Object ID() {

            return id;

        }

 

        public String NAME() {

            return name;

        }

 

        public int ARABIC() {

            return arabic;

        }

 

        public boolean isAscOver() {

            return this.arabic >= 12;

        }

 

        public boolean isAscOver(int over) {

            return this.arabic >= over;

        }

 

        public boolean isOver(int over) {

            return this.arabic > over;

        }

 

        public boolean isDescOver() {

            return this.arabic <= 1;

        }

 

        public Month increment() {

            if (this.arabic == 12) {

                return MONTH[this.arabic];

            }

            return MONTH[this.arabic + 1];

        }

 

        public Month decrement() {

            if (this.arabic == 1) {

                return MONTH[this.arabic];

            }

            return MONTH[this.arabic - 1];

        }

 

        public static Month getMonth(int month) {

            switch (month) {

                case 1:

                    return Month.JANUARY;

                case 2:

                    return Month.FEBRUARY;

                case 3:

                    return Month.MARCH;

                case 4:

                    return Month.APRIL;

                case 5:

                    return Month.MAY;

                case 6:

                    return Month.JUNE;

                case 7:

                    return Month.JULY;

                case 8:

                    return Month.AUGUST;

                case 9:

                    return Month.SEPTEMBER;

                case 10:

                    return Month.OCTOBER;

                case 11:

                    return Month.NOVEMBER;

                case 12:

                    return Month.DECEMBER;

                default:

                    return Month.NEW_YEAR;

            }

 

        }

    }

 

    /**

     * Example: getSystemDate();

     * 

     * return Date

     * 

     * @param format

     * @return

     */

    public static Date getSystemDate() {

        Date date;

        return new Date();

    }

 

    /**

     * Example: getSystemDate("yyyyMMdd");

     * 

     * return 20110820

     * 

     * @param format

     * @return

     */

    public static String getSystemDateString(String format) {

        return formatDate(new Date(), format);

    }

 

    /**

     * Example: getCurrentTime();

     * 

     * return 20110820101010222

     * 

     * @param

     * @return

     */

    public static String getCurrentTime() {

        return getSystemDateString(YYYYMMDDHHMMSSSSS);

    }

 

    /**

     * Example: formatDate(date, "yyyyMMdd");

     * 

     * date = 2011/01/02, return 20110102

     * 

     * @param date

     * @param format

     * @return

     */

    public static String formatDate(Date date, String format) {

        final SimpleDateFormat sdf = new SimpleDateFormat(format);

 

        if (date == null)

            return null;

 

        return sdf.format(date);

    }

 

    /**

     * Example: format("2011/01/10", "yyyy/MM/dd", "yyyy.MM.dd");

     * 

     * return 2011.01.10

     * 

     * @param dateString

     * @param srcFormat

     * @param targetFormat

     * @return

     */

    public static String formatDate(String dateString, String srcFormat, String targetFormat) {

        final SimpleDateFormat sdf = new SimpleDateFormat(srcFormat);

 

        Date date = null;

        try {

            if (StringUtils.isNotBlank(dateString))

                date = sdf.parse(dateString);

        } catch (ParseException e) {

        }

 

        return formatDate(date, targetFormat);

    }

 

    public static Date getDateFromStr(String dateString, String srcFormat) {

        final SimpleDateFormat sdf = new SimpleDateFormat(srcFormat);

 

        Date date = null;

        try {

            if (StringUtils.isNotBlank(dateString))

                date = sdf.parse(dateString);

        } catch (ParseException e) {

        }

 

        return date;

    }

 

    /**

     * add month

     * 

     * @param currentDate

     * @param num

     * @return

     */

    public Date getMonth(Date currentDate, int num) {

        GregorianCalendar cal = new GregorianCalendar();

        cal.setTime(currentDate);

        cal.add(GregorianCalendar.MONTH, num);// 在月份上加

        return cal.getTime();

    }

 

    /**

     * get year

     * 

     * @param currentDate

     * @param num

     * @return

     */

    public Date getYear(Date currentDate, int num) {

        GregorianCalendar cal = new GregorianCalendar();

        cal.setTime(currentDate);

        cal.add(GregorianCalendar.YEAR, num);// 在年上加

        return cal.getTime();

    }

 

    /**

     * get year

     * 

     * @param currentDate

     * @return int

     */

    public static int getYear(Date currentDate) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(currentDate);

        return calendar.get(Calendar.YEAR);

    }

 

    /**

     * get month

     * 

     * @param currentDate

     * @return int

     */

    public static int getMonth(Date currentDate) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(currentDate);

        return calendar.get(Calendar.MONTH) + 1;

    }

 

    public static int getDayOfMonth(Date currentDate) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(currentDate);

        return calendar.get(Calendar.DAY_OF_MONTH);

    }

 

    public static int getHourOfDay(Date currentDate) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(currentDate);

        return calendar.get(Calendar.HOUR_OF_DAY);

    }

 

    public static int getHour(Date currentDate) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(currentDate);

        return calendar.get(Calendar.HOUR);

    }

 

    public static String getAoP(Date currentDate) {

        if (getHourOfDay(currentDate) > 12) {

            return "PM";

        } else {

            return "AM";

        }

    }

 

    public static int getMinute(Date currentDate) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(currentDate);

        return calendar.get(Calendar.MINUTE);

    }

 

    public static String getMinute(Date currentDate, boolean flag) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(currentDate);

        flag = calendar.get(Calendar.MINUTE) < 10 && flag;

        if (flag) {

            return "0" + calendar.get(Calendar.MINUTE);

        } else {

            return "" + calendar.get(Calendar.MINUTE);

        }

    }

 

    public static Date getThisYearStart(int year) {

        calendar.set(year, 0, 1, 0, 0, 0);

        return calendar.getTime();

    }

 

    public static Date getThisYearEnd(int year) {

        calendar.set(year, 11, 31, 23, 59, 59);

        return calendar.getTime();

    }

 

    public static java.sql.Date fromUtilToSql(Date date) {

        java.sql.Date sqlDate = new java.sql.Date(date.getTime());

        return sqlDate;

    }

 

    public static boolean greaterThan(Date sender, Date receiver) {

        boolean flag = fromUtilToSql(sender).after(fromUtilToSql(receiver));

        return flag;

    }

 

    // 传入的月不要减一

    public static Date getThisMonthStart(int year, int month) {

        calendar.set(year, month - 1, 1, 00, 00, 00);

        return calendar.getTime();

    }

 

    // 传入的月不要减一

    public static Date getThisMonthStart(Date currentDate) {

        return getThisMonthStart(getYear(currentDate), getMonth(currentDate));

    }

 

    public static Date getThisMonthEnd(int year, int month) {

        return subDays(getThisMonthStart(year, month + 1), 1);

    }

 

    public static Date getThisMonthEnd(Date currentDate) {

        return subDays(getThisMonthStart(getYear(currentDate), getMonth(currentDate) + 1), 1);

    }

 

    public static Date addMonth(Date date, int amount) {

        return org.apache.commons.lang.time.DateUtils.addMonths(date, amount);

    }

 

    public static Date subMonths(Date date, int amount) {

        amount = 0 - amount;

        return org.apache.commons.lang.time.DateUtils.addMonths(date, amount);

    }

 

    public static Date addDays(Date date, int amount) {

        return org.apache.commons.lang.time.DateUtils.addDays(date, amount);

    }

 

    public static Date subDays(Date date, int amount) {

        amount = 0 - amount;

        return org.apache.commons.lang.time.DateUtils.addDays(date, amount);

    }

 

    public static List<DateBean> getEveryYear(Date start, Date end) {

        List<DateBean> list = new ArrayList<DateUtils.DateBean>();

        int startYear = getYear(start);

        int endYear = getYear(end);

        for (int i = startYear; i <= endYear; i++) {

            DateUtils.DateBean dateBean = new DateUtils.DateBean();

            if (i == startYear) {

                dateBean.setStart(getThisMonthStart(start));

            } else {

                dateBean.setStart(getThisYearStart(i));

            }

            if (i == endYear) {

                dateBean.setEnd(getThisMonthStart(endYear, getMonth(end) + 1));

            } else {

                dateBean.setEnd(getThisYearEnd(i));

            }

            list.add(dateBean);

        }

        return list;

    }

}

 
/************************************************************************/
应用例 -- 最近六个月,有跨年可能,解决方案 以年为单位 DateUtils.getEveryYear(beginDate, thisYear)
需要common-lang-2.4.jar
    /**
     * 最近6个月故障统计
     * 
     * @param thisYear
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> findFailureVolume(Date thisYear) throws Exception {
        int space = 6;
        Date beginDate = DateUtils.getThisMonthStart(DateUtils.subMonths(thisYear, space - 1));
        List<DateUtils.DateBean> listDate = DateUtils.getEveryYear(beginDate, thisYear);
        DateUtils.Month month = null;
        List<Map<String, Object>> dataList = null;
        List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < listDate.size(); i++) {
            dataList = failureDao.findFailuresEveryMonth(listDate.get(i).getStart(), listDate.get(i).getEnd());
            int start = DateUtils.getMonth(listDate.get(i).getStart());
            int end = DateUtils.getMonth(listDate.get(i).getEnd());
            int year = DateUtils.getYear(listDate.get(i).getStart());
            month = DateUtils.Month.getMonth(start - 1);
            month: while (!month.isAscOver(end - 1)) {
                month = month.increment();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("month", month.ARABIC());
                for (int j = 0; j < dataList.size(); j++) {
                    Map<String, Object> dataMap = dataList.get(j);
                    boolean flag = Integer.valueOf(dataMap.get("month").toString()).equals(month.ARABIC());
                    if (flag) {// 有值
                        map.put("year", dataMap.get("year"));
                        map.put("volume", dataMap.get("volume"));
                        returnList.add(map);
                        continue month;
                    }
                }
                // 无值
                map.put("year", year);
                map.put("volume", 0);
                returnList.add(map);
            }
        }
        return returnList;
    }
分享到:
评论

相关推荐

    Java utils资源包

    1 输入流转换为xml字符串 2 获取cookie 3 时间处理 4 雪花算法 5 json转换 6 oss工具 7.oss文件处理 8 拼音工具 9 sms短信工具 10 validate工具 8

    javautil工具类大全

    自己总结的java工具类,包括异常、文件、字符串、时间、http、搜索、进程、poi、反射、邮件、静态页面、spring、redis、权限递归、加解密,签名、校验码、json等等

    UtilsDate.java

    JAVA封装时间Utils 里面包含各种时间计算转换

    Java.LJ.TimeHelper.utils-1.1.0.jar

    这是一款可以适配JavaScript支持的大部分格式的时间,并且会将其转换成java中的指定格式时间与数据库的时间类型对应,我们可以直接将获取的各种格式的时间参数传入指定的方法中不用关心实现自动帮助我们转换成数据库...

    cron-utils:用于解析,验证和人类可读描述以及日期时间互操作性的Cron utils

    cron-utils是一个Java库,用于定义,解析,验证,迁移cron以及获取其可读的描述。 该项目遵循,提供OSGi元数据并使用Apache 2.0许可证。 下载 cron-utils在存储库中可用。 &lt;groupId&gt;com.cronutils&lt;/groupId&gt; ...

    elasticsearch工具包ESUtils.java

    elasticsearch搜索工具包,常用接口封装,可直接用于项目进行基于elasticsearch的搜索,分页、查询、初始化、创建索引、以及索引的增、删、改、查都封装成普通接口。

    CronUtils.java

    用java编写的生成cron表达式工具类,支持生成各种cron表达式,共10个方法,且支持参数定制化和输出格式定制化,下载后不满意找我

    百度翻译源码java-Architecture-Utils:Architecture-Utils

    百度翻译源码java Architecture-Utils Lambda 到 Kappa 河童建筑 建筑 Apache Icebreg vs apache hudi vs Delta Lake 阿切箭头: 时间序列数据库 spark (Flint) 很棒的大数据 一个很棒的大数据框架、资源和其他很棒...

    birth-death-process:连续时间马尔可夫过程,生死过程的特殊情况的Java仿真utils

    出生死亡过程 连续时间马尔可夫过程(出生-死亡过程)特殊情况的Java仿真实用程序。

    czy-study-java-commons-utils:java工具类:Excel导入导出、时间操作、文件上传等工具类

    czy-nexus-commons-utils (本库)[ 、 公共仓库的管理库。 (csdn教程博客)[ (github工具类集库)[] (开源中国)[] 推荐使用最新版本: &lt;!-- maven:... &lt;artifactId&gt;java-excel-utils&lt;

    RedisUtil.java

    RedisUtil:Redis工具类 指定缓存失效时间,根据key 获取过期时间,判断key是否存在,删除缓存,普通缓存获取,普通缓存放入,普通缓存放入并设置时间等

    DateUtils.java

    日期工具类,提供了大量的日期格式转换。 提供了获取本周的开始时间、结束时间、获取当前时间到指定时间的天数。 得到当前是星期几等等。

    java时间处理工具类--CalendarUtil(java源码)

    package com.hexiang.utils; import java.text.SimpleDateFormat; import java.util.*; public class CalendarUtil { public static void main(String args[]) { System.out.println("First day of week is :...

    Java实现Excel导入导出

    new Object[]{"销售单号", "销售时间", "会员", "商品总额", "来源", "商品名称/属性", "数量", "单价"}); for (ShOutOrderDetail item : list) { empinfo.put(index++, new Object[]{ item.getOutOrderNo(), ...

    TimeUtils.java

    时间转换工具类,实现日期格式与时间戳互转,获取任意(年、月、日)的开始、结束时间; 任意时间格式向前,向后移动任意跨度的时间集合等;

    java-util大全.rar

    java各种util整理-包含: AES加解密,Date时间处理,Des加解密,Emoji表情,Http请求,Json处理,MD5加密,FastDfs文件服务器,RSA加解密加解签名,线程工具类;

    JDBCUtils.java

    在最近的一段时间开始学习java,所以在数据库连接的这一块就使用了JDBC没有使用框架,但是发现一个好的JDBC工具类也不是那么好写,把自己的记录下来以便以后学习和提高

    Java整理的基础工具类项目

    Java整理的基础工具类项目 Spring+Redis实现无缝读写分离插入(com.shawntime.utils.rwdb) Redis操作封装(com.shawntime.utils.cache.redis) Redis分布式锁实现(com.shawntime.utils.lock) 读写锁控制强制读取...

    java时间处理工具类--DateUtils

    package com.hexiang.utils; /** * @(#)DateUtil.java * * * @author kidd * @version 1.00 2007/8/8 */ import java.util.*; import java.text.*; import java.sql.Timestamp; public class DateUtils { ...

Global site tag (gtag.js) - Google Analytics