DateUtil

/**
 * @Title: DateUtil.java
 * @Package com.niewj.util
 * @Description: 日期工具
 * @author niewj
 * @date 2016年8月22日 下午1:48:11
 * @version V1.0
 */
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author niewj
 * @ClassName: com.niewj.util.DateUtil
 * @Description: 日期工具類
 * @date 2016年8月22日 下午1:48:11
 */
public class DateUtil {

    private static final String dtFormat = "yyyy-MM-dd";

    /**
     * 計算當前月的天數
     *
     * @Title: currentMonthDays
     * @Description: 計算當前月的天數
     * @Since: 2016年8月22日 下午2:28:25
     * @Author: niewj
     */
    public static int currentMonthDays() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        return cal.getActualMaximum(Calendar.DATE);
    }

    /**
     * 計算回溯count個月的月份列表;
     * 比如當前為9月,count=12, 會返回:["201608",........"201509"]
     *
     * @param count 月份數-往前推
     * @return
     * @throws
     * @Title: getMonthsDateList
     * @Description: 計算當前月的天數
     * @Since: 2016年9月21日 下午2:28:25
     * @Author: niewj
     */
    public static List<String> getMonthsDateList(int count) {
        List<String> list = new ArrayList<String>();

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);

        // #1. 從上一個月開始
        int month = cal.get(Calendar.MONTH); // JANUARY is 0[1月 == 0],所以不用減一

        String monthString = null;
        for (int i = 1; i <= count; i++) {
            // #2. 如果月份小于1 [年減一 && 定位到12月]
            if (month < 1) {
                year--;
                month = 12;
            }

            // # 月份格式為2位的.
            if (month < 10) {
                list.add(year + "0" + month);
            } else {
                list.add(year + "" + month);
            }

            // # 3. 計算上一個月的;
            month--;

        }
        return list;
    }


    /**
     * 計算N個月后的全月日期表示列表; 參數接受負數,表示幾個月前
     * 比如當前為9月,會返回:["2016-09-01",........"2016-09-30"]
     *
     * @param nMonthsLater
     * @return
     * @throws
     * @Title: currentMonthDates
     * @Description: 計算當前月的天數
     * @Since: 2016年9月21日 下午2:28:25
     * @Author: niewj
     */
    public static List<String> getAllMonthDateList(int nMonthsLater) {
        final String format = "yyyy-MM-";
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, nMonthsLater);
        int daysCurMonth = cal.getActualMaximum(Calendar.DATE); // 當月最大日期

        String dt = new SimpleDateFormat(format).format(cal.getTime());

        List<String> dtList = new ArrayList<String>(daysCurMonth);
        for (int i = 1; i <= daysCurMonth; i++) {
            if (i < 10) {
                dtList.add(dt + "0" + i);
            } else {
                dtList.add(dt + i);
            }
        }
        return dtList;
    }

    /**
     * 計算當月日期表示列表; 截止天數- 舉例[+2, 表示截止兩天后, -1表示截止昨天]
     * 比如當前為9月,會返回:["2016-09-01",........"2016-09-30"]
     *
     * @param afterDays 從1號截止到afterDays天后那天的日期
     * @Title: getCurrMonthDateList
     * @Description: 計算當前月的天數
     * @Since: 2016年9月21日 下午2:28:25
     * @Author: niewj
     */
    public static List<String> getCurrMonthDateList(int afterDays) {
        final String format = "yyyy-MM-";
        Calendar cal = Calendar.getInstance();
//        int daysCurMonth = cal.getActualMaximum(Calendar.DATE); // 當月最大日期
        cal.add(Calendar.DATE, afterDays);
        int currDay = cal.get(Calendar.DATE);

        String dt = new SimpleDateFormat(format).format(cal.getTime());

        List<String> dtList = new ArrayList<String>(currDay);
        for (int i = 1; i <= currDay; i++) {
            if (i < 10) {
                dtList.add(dt + "0" + i);
            } else {
                dtList.add(dt + i);
            }
        }
        return dtList;
    }

    /**
     * 獲取本月第N天是周幾
     *
     * @Title: getDayOfWeekMonth
     * @Description: 獲取上個月第N天是周幾(1=周一;7=周日)
     * @Since: 2016年9月18日 下午8:39:13
     * @Author: niewj
     * @Param days 上月第幾天
     */
    public static int getDayOfWeekMonth(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, days); // 當月第幾天

        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 把周日(1)定義為第7天
        if (dayOfWeek == 1) {
            return ConstUtil.SUNDAY_NUM;
        } else {
            return dayOfWeek - 1;
        }
    }

    /**
     * 獲取days天后是是周幾-接受負數表示-1表示昨天
     * @Title: getWeekdayAfterDays
     * @Description: 獲取昨天是周幾(1=周一;7=周日)
     * @Since: 2016年9月20日 下午8:39:13
     * @Author: niewj
     * @Param days 上月第幾天
     */
    public static int getWeekdayAfterDays(int days) {
        long timeMillis = new Date().getTime() + days * ConstUtil.ONE_DAY_MILLIS;
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timeMillis);

        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 把周日(1)定義為第7天
        if (dayOfWeek == 1) {
            return ConstUtil.SUNDAY_NUM;
        } else {
            return dayOfWeek - 1;
        }
    }

    /**
     * 計算本月周幾有幾天:<周一, 4天>
     */
    public static Map<Integer, Integer> getWeekdayCountMap() {
        int daysThisMonth = currentMonthDays();

        Map<Integer, Integer> weekdayCountMap = new HashMap<Integer, Integer>();
        for (int i = 1; i <= daysThisMonth; i++) {
            int weekday = getDayOfWeekMonth(i); // 計算本月第i天是周幾
            // 如果包含周i, 就+1
            if (weekdayCountMap.containsKey(weekday)) {
                weekdayCountMap.put(weekday, weekdayCountMap.get(weekday) + 1);
            } else {
                weekdayCountMap.put(weekday, 1);
            }
        }
        return weekdayCountMap;
    }

    /**
     * 獲取當前日期已經占當前月的時間進度-今天:days=0;昨天days=-1;明天days=2
     *
     * @param days 計算days天日期(1,表示明天進度; -1表示昨天)
     * @Title: getRateOfMonth
     * @Description: 獲取當前日期已經占當前月的時間進度
     * @Since: 2016年8月22日 下午2:39:13
     * @Author: niewj
     */
    public static String getRateProgressOfMonth(int days) {
        long timeMillis = new Date().getTime() + days * ConstUtil.ONE_DAY_MILLIS;
        // 1. 得到當前日期: 當前月的第幾天
        Calendar c = Calendar.getInstance();
        c.setTime(new Date(timeMillis));
        int date = c.get(Calendar.DAY_OF_MONTH);

        // 2. 當前月的天數
        int daysOfMonth = currentMonthDays();

        // 3. 計算: 保留兩位小數, 四舍五入
        DecimalFormat df = new DecimalFormat("#.00");
        String dbStr = df.format(date * 100.0 / daysOfMonth);

        return dbStr;
    }

    /**
     * 獲取上個月第N天的日期,如當前是"2016-09-18", 上月第2天返回:"2016-08-02"
     * @Title: getDateOfLastMonth
     * @Description: 獲取上個月第N天的日期
     * @Since: 2016年9月18日 下午8:39:13
     * @Author: niewj
     * @Param days 上月第幾天
     */
    public static String getDateOfLastMonth(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, days);

        SimpleDateFormat sdf = new SimpleDateFormat(dtFormat);

        return sdf.format(calendar.getTime());
    }

    /**
     * 計算指定的日期是周幾
     * @Title: getWeekdayOfDate
     * @Description: 計算指定的日期是周幾
     * @Since: 2016年9月21日 下午16:39:13
     * @Author: niewj
     * @Param dt 日期
     */
    public static int getWeekdayOfDate(String dt) {
        Date date = null;
        try {
            date = new SimpleDateFormat(dtFormat).parse(dt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        int weekday = calendar.get(Calendar.DAY_OF_WEEK);
        // 把周日(1)定義為第7天
        if (weekday == 1) {
            return ConstUtil.SUNDAY_NUM;
        } else {
            return weekday - 1;
        }
    }

    /**
     * 獲取上個月第N天是周幾-
     * @Title: getDateOfLastMonth
     * @Description: 獲取上個月第N天是周幾(1=周一;7=周日)
     * @Since: 2016年9月18日 下午8:39:13
     * @Author: niewj
     * @Param days 上月第幾天
     */
    public static int getDayOfWeekLastMonth(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, days); // 當月第幾天

        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            return ConstUtil.SUNDAY_NUM;
        } else {
            return dayOfWeek - 1;
        }
    }

    /**
     * 求指定日期的上月日期 yyyymm格式:
     * 舉例: 如給定日期是201701的Date對象,則返回"201612"
     *
     * @param date 給定的日期
     * @return 給定日期的上月日期的字符串表示yyyymm
     */
    public static String getYyyyMmLastMonth(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");

        Calendar calendar = Calendar.getInstance();
        // 設置為當前時間
        calendar.setTime(date);
        // 設置為上一個月
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        date = calendar.getTime();

        return dateFormat.format(date);
    }
    
    public static void main(String[] args) {
        System.out.println(getWeekdayAfterDays(-8));
        System.out.println(getAllMonthDateList(0));
        System.out.println(getCurrMonthDateList(-1));
        System.out.println(getWeekdayOfDate("2016-09-21"));
        System.out.println(getMonthsDateList(24));
//        Map<Integer, Integer> weekdayCountMap = getWeekdayCountMap();
//
//        for(Map.Entry<Integer, Integer> entry:weekdayCountMap.entrySet()){
//            System.out.println(entry.getKey()+"\t = "+entry.getValue());
//        }
//
//        System.out.println(getRateProgressOfMonth(-1));
//        System.out.println(getDateOfLastMonth(1));
//        System.out.println(getDateOfLastMonth(5));
//        System.out.println(getDayOfWeekLastMonth(28)); // 上月28號是周(7)

    }
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容