java时间操作相关小结(9种)

时间打磨了性子,我只能这么说。现在我都考虑一些比较持久的东西了,例如买个紫砂壶,泡制各式各样的茶叶,然后戒掉饮料和糖果。最近,也没有什么心理活动了,是不是又开始变得随和了,变得无所企及。俗话说的好:无欲则刚,有容乃大。
现附上,时间操作的9种方法小结。

    package com.css.java.learning.service;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;
    import com.css.util.DateUtil;
    import com.css.util.StringHelper;
public class RedAntDateUtil extends DateUtil {
        //设置三种常用时间格式
        public static final String FORMAT_TIMESTAMP = "yyyyMMddHHmmss";
        public static final String FORMAT_TIME = "yyyy-MM-dd HH:mm:ss";
        public static final String FORMAT_DATE = "yyyy-MM-dd";
        /**
         *1、 获取当前时间戳
         * @return
         */
        public static Long getTimestamp() {
            return new Date().getTime();
        }
        /**
         * 2、时间解析为字符串
         * @param date   为NULL时,使用系统当前时间
         * @param format 为NULL或空串时,使用FORMAT_DATE
         * @return 日期按指定类型格式化后的字符串
         */
        public static String convertDateToStr(Date date, String format) {
            Calendar cal = Calendar.getInstance();
            if (date == null) {
                return "";
            }
            cal.setTime(date);
            if (StringHelper.isEmpty(format)) {
                format = FORMAT_TIME;
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format, java.util.Locale.US);
            return sdf.format(cal.getTime());
        }

        /**
         * 3、字符串解析为时间
         * @param str    为NULL或空串时,返回NULL
         * @param format 为NULL或空串时,使用FORMAT_DATE
         * @return 字符串按指定类型格式化后的日期
         */
        public static Date convertStrToDate(String str, String format) {
            if (StringHelper.isEmpty(str)) {
                return null;
            }
            if (StringHelper.isEmpty(format)) {
                format = FORMAT_TIME;
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format, java.util.Locale.US);
            try {
                return sdf.parse(str);
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }
        }

        /**
         * 4、字符串先解析为时间,然后把时间格式化为字符串(将字符串格式化为标准格式的字符串时间)
         * @param str           为NULL或空串时,返回NULL
         * @param formatSource (输入字符串格式)为NULL或空串时,使用FORMAT_DATE
         * @param formatTarget (输出字符串格式)为NULL或空串时,使用FORMAT_DATE
         * @return 字符串按指定类型格式化后的字符串
         */
        public static String formatStr(String str, String formatSource, String formatTarget) {
            return convertDateToStr(convertStrToDate(str, formatSource), formatTarget);
        }

        /**
         * 5、得到从起始年份到今天的年份列表
         * @param startDate 输入起始时间:格式为"2018-01-01 00:00:00"
         * @throws ParseException
         */
        public static List<String> getYearList(String startDate) {
            Calendar cal = Calendar.getInstance();
            Date fromDate = convertStrToDate(startDate, null);
            cal.setTime(fromDate);
            Calendar endCal = Calendar.getInstance();
            List<String> calList = new ArrayList<String>();
            while (cal.before(endCal)) {
                calList.add(String.valueOf(cal.get(Calendar.YEAR)));
                cal.add(Calendar.YEAR, 1);// 加一年
            }
            return calList;
        }
        /**
         * 6、获取某月份,所有的周 的日期段(1-7)
         * monthOfYear 的格式为:"2017/6"
         */
        public static void getweekofMonth(String monthOfYear) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            sdf.setLenient(false);
            SimpleDateFormat sdft = new SimpleDateFormat("EEE");
            for (int i = 1; i < 32; i++) {
                try {
                    Date date = sdf.parse(monthOfYear+ "/" + i);
                System.err.println(sdf.format(date) + ":" + sdft.format(date));  

                } catch (java.text.ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        /**
         * 7、根据当前日期,获取所在周
         */
        @SuppressWarnings("static-access")
        public static Integer getTimeInterval(Date date){
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int dayWeek = cal.get(cal.DAY_OF_WEEK) - 1;//中西方,对每周的定义不同
            return dayWeek;
        }

        /**
         * 8、根据星期几来匹配当前年月对应该星期几的具体日期个数(例如:找出当前月份所有星期三的日期个数)
         * @param k  当前月份,包含星期几的数目
         * @param weekTime 星期几
         * @param seYear 年
         * @param seMonth 月
         * @return k
         */
        public static int getYearMonthContentWeek(int k, String weekTime, String seYear, String seMonth) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            SimpleDateFormat sdft = new SimpleDateFormat("EEE");
            Calendar cal = Calendar.getInstance();
            cal.set(Integer.valueOf(seYear), Integer.valueOf(seMonth), 0);
            int dayofMonth = cal.get(Calendar.DAY_OF_MONTH);
            for (int j = 1; j < dayofMonth + 1; j++) {
                try {
                    Date date = sdf.parse(seYear + "/"+ seMonth + "/" + j);
                    if(sdft.format(date).equals(weekTime)){
                        k++;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            return k;
        }
        /**
         * 9、根据出生日期, 计算当前年龄
         * @param birthday
         * @return 年龄
         */
        public static int getAgeByBirthday(String birthday) {
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            int age = 0;
            try {
                Date dateb = sdf.parse(birthday);
                if(cal.before(dateb)){//还没出生的日期
                    return 0;
                }
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int dayofMonth = cal.get(Calendar.DAY_OF_MONTH);
                cal.setTime(dateb);
                int birthYear = cal.get(Calendar.YEAR);
                int birthMonth = cal.get(Calendar.MONTH);
                int birthDayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                age = year - birthYear;
                if(month <= birthMonth){
                    if(month == birthMonth){
                        if(dayofMonth < birthDayOfMonth){
                            age--;
                        }
                    }else{
                        age--;
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
                return 0;
            }
            return age;
        }

}

希望,积累的东西可以少走点弯路。

猜你喜欢

转载自blog.51cto.com/13479739/2318116