時間段顯示

/**
     * 根據當前時間,格式化給定時間
     *
     * @param time
     * @param halfDay 是否區分上午下午
     * @return
     */
    public static String formatTimeStr(long time, boolean halfDay) {
        Calendar calendarIn = Calendar.getInstance();
        calendarIn.setTimeInMillis(time);
        Calendar calendarNow = Calendar.getInstance();
        String result;
        int daysBetween = getDaysBetween(calendarNow, calendarIn);
        switch (daysBetween) {
            case 0:
                if (halfDay) {
                    result = calendarIn.get(Calendar.HOUR_OF_DAY) >= 12 ? "今天 下午" : "今天 上午";
                } else {
                    result = Integer.toString(calendarIn.get(Calendar.HOUR_OF_DAY)) + ":" + Integer.toString(calendarIn.get(Calendar.MINUTE));
                }
                break;
            case 1:
                result = "昨天";
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
                String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
                int index = calendarIn.get(Calendar.DAY_OF_WEEK) - 1;
                index = index < 0 ? 0 : index;
                result = weeks[index];
                break;
            default:
                int year = calendarIn.get(Calendar.YEAR);
                int month = calendarIn.get(Calendar.MONTH) + 1;
                int day = calendarIn.get(Calendar.DAY_OF_MONTH);
                String dayStr = Integer.toString(day);
                String monthStr = Integer.toString(month);
                result = Integer.toString(year) + "-" + (month < 10 ? "0" + monthStr : monthStr) + "-" + (day < 10 ? "0" + dayStr : dayStr);
                break;
        }
        return result;
    }

/**
     * 計算相隔的天數
     *
     * @param d1
     * @param d2
     * @return
     */
     private static int getDaysBetween(Calendar d1, Calendar d2) {
        if (d1.after(d2)) {  // swap dates so that d1 is start and d2 is end
            java.util.Calendar swap = d1;
            d1 = d2;
            d2 = swap;
        }
        int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        int y2 = d2.get(Calendar.YEAR);
        if (d1.get(Calendar.YEAR) != y2) {
            d1 = (Calendar) d1.clone();
            do {
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);//得到當年的實際天數
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        }
        return days;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章