web開發中公用元件的開發之一DateUtils .

悠悠隱於市發表於2011-01-11
web開發中公用元件的開發之一---------DateUtils 

在web應用中我們經常要到用到對日期的操作 
已經有很多的開原始碼供選擇,例如apache 就有 
不是太複雜就是不太適合中國國情的,反正專案中很少用到apache的公用元件包 

下面是我在web開發中常用的些方法操作 
現簡單列舉出來,已示記念。 

Java程式碼 
  
package com.chinadim.test.utils;   
  
import java.text.ParsePosition;   
import java.text.SimpleDateFormat;   
import java.util.Calendar;   
import java.util.Date;   
  
  
/**  
 * xxxxx  
 * xxxxxx  
 */  
public class DateUtils {   
       
    /**  
     * 靜態常量  
     */  
    public static final String C_TIME_PATTON_DEFAULT = "yyyy-MM-dd HH:mm:ss";   
    public static final String C_DATE_PATTON_DEFAULT = "yyyy-MM-dd";   
       
    public static final int C_ONE_SECOND = 1000;   
    public static final int C_ONE_MINUTE = 60 * C_ONE_SECOND;   
    public static final long C_ONE_HOUR = 60 * C_ONE_MINUTE;   
    public static final long C_ONE_DAY = 24 * C_ONE_HOUR;   
       
    /**  
     * 計算當前月份的最大天數  
     * @return  
     */  
    public static int findMaxDayInMonth() {   
        return findMaxDayInMonth(0, 0);   
    }   
       
    /**  
     * 計算指定日期月份的最大天數  
     * @param date  
     * @return  
     */  
    public static int findMaxDayInMonth(Date date) {   
        if (date == null) {   
            return 0;   
        }   
        return findMaxDayInMonth(date2Calendar(date));   
    }   
       
    /**  
     * 計算指定日曆月份的最大天數  
     * @param calendar  
     * @return  
     */  
    public static int findMaxDayInMonth(Calendar calendar) {   
        if (calendar == null) {   
            return 0;   
        }   
           
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);   
    }   
       
    /**  
     * 計算當前年某月份的最大天數  
     * @param month  
     * @return  
     */  
    public static int findMaxDayInMonth(int month) {   
        return findMaxDayInMonth(0, month);   
    }   
       
    /**  
     * 計算某年某月份的最大天數  
     * @param year  
     * @param month  
     * @return  
     */  
    public static int findMaxDayInMonth(int year, int month) {   
        Calendar calendar = Calendar.getInstance();   
        if (year > 0) {   
            calendar.set(Calendar.YEAR, year);   
        }   
           
        if (month > 0) {   
            calendar.set(Calendar.MONTH, month - 1);   
        }   
           
        return findMaxDayInMonth(calendar);   
    }   
       
    /**  
     * Calendar 轉換為 Date  
     * @param calendar  
     * @return  
     */  
    public static Date calendar2Date(Calendar calendar) {   
        if (calendar == null) {   
            return null;   
        }   
        return calendar.getTime();   
    }   
       
    /**  
     * Date 轉換為 Calendar  
     * @param date  
     * @return  
     */  
    public static Calendar date2Calendar(Date date) {   
        if (date == null) {   
            return null;   
        }   
        Calendar calendar = Calendar.getInstance();   
        calendar.setTime(date);   
        return calendar;   
    }   
       
    /**  
     * 拿到預設格式的SimpleDateFormat  
     * @return  
     */  
    public static SimpleDateFormat getSimpleDateFormat() {   
        return getSimpleDateFormat(null);   
    }   
       
    /**  
     * 拿到指定輸出格式的SimpleDateFormat  
     * @param format  
     * @return  
     */  
    public static SimpleDateFormat getSimpleDateFormat(String format) {   
        SimpleDateFormat sdf;   
        if (format == null) {   
            sdf = new SimpleDateFormat(C_TIME_PATTON_DEFAULT);   
        } else {   
            sdf = new SimpleDateFormat(format);   
        }   
           
        return sdf;   
    }   
       
    /**  
     * 轉換當前時間為預設格式  
     * @return  
     */  
    public static String formatDate2Str() {   
        return formatDate2Str(new Date());   
    }   
       
    /**  
     * 轉換指定時間為預設格式  
     * @param date  
     * @return  
     */  
    public  static String formatDate2Str(Date date) {   
        return formatDate2Str(date, C_TIME_PATTON_DEFAULT);   
    }   
       
    /**  
     * 轉換指定時間為指定格式  
     * @param date  
     * @param format  
     * @return  
     */  
    public static String formatDate2Str(Date date, String format) {   
        if (date == null) {   
            return null;   
        }   
           
        if (format == null || format.equals("")) {   
            format = C_TIME_PATTON_DEFAULT;   
        }   
        SimpleDateFormat sdf = getSimpleDateFormat(format);   
        return sdf.format(date);   
    }   
       
    /**  
     * 轉換預設格式的時間為Date  
     * @param dateStr  
     * @return  
     */  
    public static Date formatStr2Date(String dateStr) {   
        return formatStr2Date(dateStr, null);   
    }   
       
    /**  
     * 轉換指定格式的時間為Date  
     * @param dateStr  
     * @param format  
     * @return  
     */  
    public static Date formatStr2Date(String dateStr, String format) {   
        if (dateStr == null) {   
            return null;   
        }   
           
        if (format == null || format.equals("")) {   
            format = C_TIME_PATTON_DEFAULT;   
        }   
        SimpleDateFormat sdf = getSimpleDateFormat(format);   
        return sdf.parse(dateStr, new ParsePosition(0));   
    }   
       
    /**  
     * 轉換預設格式的時間為指定格式時間  
     * @param dateStr  
     * @param defineFormat  
     * @return  
     */  
    public static String formatDefault2Define(String dateStr, String defineFormat) {   
        return formatSource2Target(dateStr, C_TIME_PATTON_DEFAULT, defineFormat);   
    }   
       
    /**  
     * 轉換源格式的時間為目標格式時間  
     * @param dateStr  
     * @param sourceFormat  
     * @param targetFormat  
     * @return  
     */  
    public static String formatSource2Target(String dateStr, String sourceFormat, String targetFormat) {   
        Date date = formatStr2Date(dateStr, sourceFormat);   
        return formatDate2Str(date, targetFormat);   
    }   
       
    /**  
     * 計算當天是該年中的第幾周  
     * @return  
     */  
    public static int findWeeksNoInYear() {   
        return findWeeksNoInYear(new Date());   
    }   
       
    /**  
     * 計算指定日期是該年中的第幾周  
     * @param date  
     * @return  
     */  
    public static int findWeeksNoInYear(Date date) {   
        if (date == null) {   
            return 0;   
        }   
        return findWeeksNoInYear(date2Calendar(date));   
    }   
       
    /**  
     * 計算指定日曆是該年中的第幾周  
     * @param calendar  
     * @return  
     */  
    public static int findWeeksNoInYear(Calendar calendar) {   
        if (calendar == null) {   
            return 0;   
        }   
        return calendar.get(Calendar.WEEK_OF_YEAR);   
    }   
       
    /**  
     * 計算一年中的第幾星期是幾號   
     * @param year  
     * @param weekInYear  
     * @param dayInWeek  
     * @return  
     */  
    public static Date findDateInWeekOnYear(int year, int weekInYear, int dayInWeek) {   
        Calendar calendar = Calendar.getInstance();   
        if (year > 0) {   
            calendar.set(Calendar.YEAR, year);   
        }   
           
        calendar.set(Calendar.WEEK_OF_YEAR, weekInYear);   
        calendar.set(Calendar.DAY_OF_WEEK, dayInWeek);   
           
        return calendar.getTime();   
    }   
       
    /**  
     * 相對於當前日期的前幾天(days < 000000)或者後幾天(days > 0)  
     * @param days  
     * @return  
     */  
    public static Date dayBefore2Date(int days) {    
        Date date = new Date();   
        return dayBefore2Object(days, null, date);   
    }   
       
    /**  
     * 相對於當前日期的前幾天(days < 000000)或者後幾天(days > 0)  
     * @param days  
     * @return  
     */  
    public static String dayBefore2Str(int days) {   
        String string = formatDate2Str();   
        return dayBefore2Object(days, null, string);   
    }   
       
    /**  
     * 相對於當前日期的前幾天(days < 000000)或者後幾天(days > 0)  
     * @param days  
     * @param format  
     * @param instance  
     */  
    @SuppressWarnings("unchecked")   
    public static <T extends Object> T dayBefore2Object(int days, String format, T instance) {   
        Calendar calendar = Calendar.getInstance();   
        if (days == 0) {   
            return null;   
        }   
           
        if (format == null || format.equals("")) {   
            format = C_TIME_PATTON_DEFAULT;   
        }   
           
        calendar.add(Calendar.DATE, days);   
        if (instance instanceof Date) {   
            return (T)calendar.getTime();   
        } else if (instance instanceof String) {   
            return (T)formatDate2Str(calendar2Date(calendar), format);   
        }   
        return null;   
    }   
       
    /**  
     * 相對於指定日期的前幾天(days < 000000)或者後幾天(days > 0)  
     * @param date  
     * @param days  
     * @return  
     */  
    public static Date defineDayBefore2Date(Date date, int days) {   
        Date dateInstance = new Date();   
        return defineDayBefore2Object(date, days, null, dateInstance);   
    }   
       
    /**  
     * 相對於指定日期的前幾天(days < 000000)或者後幾天(days > 0)  
     * @param date  
     * @param days  
     * @return  
     */  
    public static String defineDayBefore2Str(Date date, int days) {   
        String stringInstance = formatDate2Str();   
        return defineDayBefore2Object(date, days, null, stringInstance);   
    }   
       
    /**  
     * 相對於指定日期的前幾天(days < 000000)或者後幾天(days > 0)  
     * @param <T>  
     * @param date  
     * @param days  
     * @param format  
     * @param instance  
     * @return  
     */  
    @SuppressWarnings("unchecked")   
    public static <T extends Object> T defineDayBefore2Object(Date date,    
            int days, String format, T instance) {   
        if (date == null || days == 0) {   
            return null;   
        }   
           
        if (format == null || format.equals("")) {   
            format = C_TIME_PATTON_DEFAULT;   
        }   
           
        Calendar calendar = date2Calendar(date);   
        calendar.add(Calendar.DATE, days);   
        if (instance instanceof Date) {   
            return (T)calendar.getTime();   
        } else if (instance instanceof String) {   
            return (T)formatDate2Str(calendar2Date(calendar), format);   
        }   
        return null;   
    }   
       
    /**  
     * 相對於當前日期的前幾月(months < 000000)或者後幾月(months > 0)時間  
     * @param months  
     * @return  
     */  
    public static Date monthBefore2Date(int months) {   
        Date date = new Date();   
        return monthBefore2Object(months, null, date);   
    }   
       
    /**  
     * 相對於當前日期的前幾月(months < 000000)或者後幾月(months > 0)時間  
     * @param months  
     * @return  
     */  
    public static String monthBefore2Str(int months) {   
        String string = formatDate2Str();   
        return monthBefore2Object(months, null, string);   
    }   
       
    /**  
     * 相對於當前日期的前幾月(months < 000000)或者後幾月(months > 0)時間  
     * @param <T>  
     * @param months  
     * @param format  
     * @param instance  
     */  
    @SuppressWarnings("unchecked")   
    public static <T extends Object> T monthBefore2Object(int months, String format, T instance) {   
        if (months == 0) {   
            return null;   
        }   
           
        if (format == null || format.equals("")) {   
            format = C_TIME_PATTON_DEFAULT;   
        }   
        Calendar calendar = Calendar.getInstance();   
        calendar.add(Calendar.MONTH, months);   
           
        if (instance instanceof Date) {   
            return (T)calendar.getTime();   
        } else if (instance instanceof String) {   
            return (T)formatDate2Str(calendar2Date(calendar), format);   
        }   
           
        return null;   
    }   
       
    /**  
     * 相對於指定日期的前幾月(months < 000000)或者後幾月(months > 0)時間  
     * @param date  
     * @param months  
     * @return  
     */  
    public static Date defineMonthBefore2Date(Date date, int months) {   
        Date dateInstance = new Date();   
        return defineMonthBefore2Object(date, months, null, dateInstance);   
    }   
       
    /**  
     * 相對於指定日期的前幾月(months < 000000)或者後幾月(months > 0)時間  
     * @param date  
     * @param months  
     * @return  
     */  
    public static String defineMonthBefore2Str(Date date, int months) {   
        String stringInstance = formatDate2Str();   
        return defineMonthBefore2Object(date, months, null, stringInstance);   
    }   
       
    /**  
     * 相對於指定日期的前幾月(months < 000000)或者後幾月(months > 0)時間  
     * @param <T>  
     * @param date  
     * @param months  
     * @param format  
     * @param instance  
     * @return  
     */  
    @SuppressWarnings("unchecked")   
    public static <T extends Object> T defineMonthBefore2Object(Date date,   
            int months, String format, T instance) {   
        if (months == 0) {   
            return null;   
        }   
           
        if (format == null || format.equals("")) {   
            format = C_TIME_PATTON_DEFAULT;   
        }   
           
        Calendar calendar = date2Calendar(date);   
        calendar.add(Calendar.MONTH, months);   
           
        if (instance instanceof Date) {   
            return (T)calendar.getTime();   
        } else if (instance instanceof String) {   
            return (T)formatDate2Str(calendar2Date(calendar), format);   
        }   
           
        return null;   
    }   
       
    /**  
     * 計算兩個日期直接差的天數  
     * @param firstDate  
     * @param secondDate  
     * @return  
     */  
    public static int caculate2Days(Date firstDate, Date secondDate) {   
        Calendar calendar = Calendar.getInstance();   
        calendar.setTime(firstDate);   
        int dayNum1 = calendar.get(Calendar.DAY_OF_YEAR);   
        calendar.setTime(secondDate);   
        int dayNum2 = calendar.get(Calendar.DAY_OF_YEAR);   
        return Math.abs(dayNum1 - dayNum2);   
    }   
       
    /**  
     * 計算兩個日期直接差的天數  
     * @param firstCalendar  
     * @param secondCalendar  
     * @return  
     */  
    public static int caculate2Days(Calendar firstCalendar, Calendar secondCalendar) {   
        if (firstCalendar.after(secondCalendar)) {   
            Calendar calendar = firstCalendar;   
            firstCalendar = secondCalendar;   
            secondCalendar = calendar;   
        }   
           
        long calendarNum1 = firstCalendar.getTimeInMillis();   
        long calendarNum2 = secondCalendar.getTimeInMillis();   
        return Math.abs((int)((calendarNum1 - calendarNum2)/C_ONE_DAY));   
    }   
       
    public static void main(String[] args) {   
//      System.out.println("當前月份的最大天數:" + findMaxDayInMonth(new Date()));   
//      System.out.println("6月份的最大天數:" + findMaxDayInMonth(6));   
//      System.out.println("1999-02月份的最大天數:" + findMaxDayInMonth(1999, 2));   
//      System.out.println("2000-02月份的最大天數:" + findMaxDayInMonth(2000, 2));   
           
//      System.out.println(formatSource2Target("2009-07-24 11:02:35", null, "yyyy/MM/dd"));   
//      System.out.println(findWeeksNoInYear());   
           
//      System.out.println("2003年的第30個星期一是那天:" + findDateInWeekOnYear(2003, 30, Calendar.MONDAY));   
//      System.out.println("2009年的第30個星期一是那天:" + findDateInWeekOnYear(2009, 30, Calendar.FRIDAY));   
           
//      System.out.println("【日期格式】當前日期的前7天是:" + dayBefore2Date(-7));   
//      System.out.println("【字元格式】當前日期的前7天是:" + dayBefore2Str(-7));   
//      System.out.println("【日期格式】當前日期的後7天是:" + dayBefore2Date(7));   
//      System.out.println("【字元格式】當前日期的後7天是:" + dayBefore2Str(7));   
           
//      System.out.println(formatStr2Date("2009-07-22", "yyyy-MM-dd"));   
           
//      System.out.println("【日期格式】2009-07-22的前7天是:" +    
//              defineDayBefore2Date(formatStr2Date("2009-07-22", "yyyy-MM-dd"), -7));   
//      System.out.println("【字元格式】2009-07-22的前7天是:" +    
//              defineDayBefore2Str(formatStr2Date("2009-07-22", "yyyy-MM-dd"), -7));   
//      System.out.println("【日期格式】2009-07-22的後7天是:" +    
//              defineDayBefore2Date(formatStr2Date("2009-07-22", "yyyy-MM-dd"), 7));   
//      System.out.println("【字元格式】2009-07-22的後7天是:" +    
//              defineDayBefore2Str(formatStr2Date("2009-07-22", "yyyy-MM-dd"), 7));   
           
//      System.out.println("【日期格式】相對於當前時間的前2月日期是:" + monthBefore2Date(-2));   
//      System.out.println("【字元格式】相對於當前時間的前2月日期是:" + monthBefore2Date(-2));   
//      System.out.println("【日期格式】相對於當前時間的後2月日期是:" + monthBefore2Date(2));   
//      System.out.println("【字元格式】相對於當前時間的後2月日期是:" + monthBefore2Date(2));   
           
//      System.out.println("【日期格式】2009-07-22的前2月日期是:" +    
//              defineMonthBefore2Date(formatStr2Date("2009-07-22", "yyyy-MM-dd"), -2));   
//      System.out.println("【字元格式】2009-07-22的前2月日期是:" +   
//              defineMonthBefore2Date(formatStr2Date("2009-07-22", "yyyy-MM-dd"), -2));   
//      System.out.println("【日期格式】2009-07-22的後2月日期是:" +    
//              defineMonthBefore2Date(formatStr2Date("2009-07-22", "yyyy-MM-dd"), 2));   
//      System.out.println("【字元格式】2009-07-22的後2月日期是:" +    
//              defineMonthBefore2Date(formatStr2Date("2009-07-22", "yyyy-MM-dd"), 2));   
           
//      Date firstDate = formatStr2Date("2009-07-22", "yyyy-MM-dd");   
//      Date secondDate = formatStr2Date("2009-07-18", "yyyy-MM-dd");   
//      System.out.println(caculate2Days(firstDate, secondDate));   
           
        Calendar firstC = date2Calendar(formatStr2Date("2009-07-22", "yyyy-MM-dd"));   
        Calendar secondC = date2Calendar(formatStr2Date("2009-07-18", "yyyy-MM-dd"));   
        System.out.println(caculate2Days(firstC, secondC));   
    }   
}  

 

相關文章