Java日期操作工具類

jopen 11年前發布 | 48K 次閱讀 Java Java開發

日期操作工具類,主要實現了日期的常用操作。在工具類中經常使用到工具類的格式化描述,這個主要是一個日期的操作類,所以日志格式主要使用 SimpleDateFormat的定義格式.

  /**

 * 格式化日期顯示格式
 *
 * @param sdate
 *            原始日期格式 s - 表示 "yyyy-mm-dd" 形式的日期的 String 對象
 * @param format
 *            格式化后日期格式
 * @return 格式化后的日期顯示
 */
public static String dateFormat(String sdate, String format) {
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    java.sql.Date date = java.sql.Date.valueOf(sdate);
    String dateString = formatter.format(date);

    return dateString;
}

/**
 * 求兩個日期相差天數
 *
 * @param sd
 *            起始日期,格式yyyy-MM-dd
 * @param ed
 *            終止日期,格式yyyy-MM-dd
 * @return 兩個日期相差天數
 */
public static long getIntervalDays(String sd, String ed) {
    return ((java.sql.Date.valueOf(ed)).getTime() - (java.sql.Date
            .valueOf(sd)).getTime()) / (3600 * 24 * 1000);
}

/**
 * 起始年月yyyy-MM與終止月yyyy-MM之間跨度的月數。
 *
 * @param beginMonth
 *            格式為yyyy-MM
 * @param endMonth
 *            格式為yyyy-MM
 * @return 整數。
 */
public static int getInterval(String beginMonth, String endMonth) {
    int intBeginYear = Integer.parseInt(beginMonth.substring(0, 4));
    int intBeginMonth = Integer.parseInt(beginMonth.substring(beginMonth
            .indexOf("-") + 1));
    int intEndYear = Integer.parseInt(endMonth.substring(0, 4));
    int intEndMonth = Integer.parseInt(endMonth.substring(endMonth
            .indexOf("-") + 1));

    return ((intEndYear - intBeginYear) * 12)
            + (intEndMonth - intBeginMonth) + 1;
}

/**
 * 根據給定的分析位置開始分析日期/時間字符串。例如,時間文本 "07/10/96 4:5 PM, PDT" 會分析成等同于
 * Date(837039928046) 的 Date。
 *
 * @param sDate
 * @param dateFormat
 * @return
 */
public static Date getDate(String sDate, String dateFormat) {
    SimpleDateFormat fmt = new SimpleDateFormat(dateFormat);
    ParsePosition pos = new ParsePosition(0);

    return fmt.parse(sDate, pos);
}

/**
 * 取得當前日期的年份,以yyyy格式返回.
 *
 * @return 當年 yyyy
 */
public static String getCurrentYear() {
    return getFormatCurrentTime("yyyy");
}

/**
 * 自動返回上一年。例如當前年份是2007年,那么就自動返回2006
 *
 * @return 返回結果的格式為 yyyy
 */
public static String getBeforeYear() {
    String currentYear = getFormatCurrentTime("yyyy");
    int beforeYear = Integer.parseInt(currentYear) - 1;
    return "" + beforeYear;
}

/**
 * 取得當前日期的月份,以MM格式返回.
 *
 * @return 當前月份 MM
 */
public static String getCurrentMonth() {
    return getFormatCurrentTime("MM");
}

/**
 * 取得當前日期的天數,以格式"dd"返回.
 *
 * @return 當前月中的某天dd
 */
public static String getCurrentDay() {
    return getFormatCurrentTime("dd");
}

/**
 * 返回當前時間字符串。
 * <p>
 * 格式:yyyy-MM-dd
 *
 * @return String 指定格式的日期字符串.
 */
public static String getCurrentDate() {
    return getFormatDateTime(new Date(), "yyyy-MM-dd");
}

/**
 * 返回當前指定的時間戳。格式為yyyy-MM-dd HH:mm:ss
 *
 * @return 格式為yyyy-MM-dd HH:mm:ss,總共19位。
 */
public static String getCurrentDateTime() {
    return getFormatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss");
}

/**
 * 返回給定時間字符串。
 * <p>
 * 格式:yyyy-MM-dd
 *
 * @param date
 *            日期
 * @return String 指定格式的日期字符串.
 */
public static String getFormatDate(Date date) {
    return getFormatDateTime(date, "yyyy-MM-dd");
}

/**
 * 根據制定的格式,返回日期字符串。例如2007-05-05
 *
 * @param format
 *            "yyyy-MM-dd" 或者 "yyyy/MM/dd",當然也可以是別的形式。
 * @return 指定格式的日期字符串。
 */
public static String getFormatDate(String format) {
    return getFormatDateTime(new Date(), format);
}

/**
 * 返回當前時間字符串。
 * <p>
 * 格式:yyyy-MM-dd HH:mm:ss
 *
 * @return String 指定格式的日期字符串.
 */
public static String getCurrentTime() {
    return getFormatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss");
}

/**
 * 返回給定時間字符串。
 * <p>
 * 格式:yyyy-MM-dd HH:mm:ss
 *
 * @param date
 *            日期
 * @return String 指定格式的日期字符串.
 */
public static String getFormatTime(Date date) {
    return getFormatDateTime(date, "yyyy-MM-dd HH:mm:ss");
}

/**
 * 返回給短時間字符串。
 * <p>
 * 格式:yyyy-MM-dd
 *
 * @param date
 *            日期
 * @return String 指定格式的日期字符串.
 */
public static String getFormatShortTime(Date date) {
    return getFormatDateTime(date, "yyyy-MM-dd");
}

/**
 * 根據給定的格式,返回時間字符串。
 * <p>
 * 格式參照類描繪中說明.和方法getFormatDate是一樣的。
 *
 * @param format
 *            日期格式字符串
 * @return String 指定格式的日期字符串.
 */
public static String getFormatCurrentTime(String format) {
    return getFormatDateTime(new Date(), format);
}

/**
 * 根據給定的格式與時間(Date類型的),返回時間字符串。最為通用。<br>
 *
 * @param date
 *            指定的日期
 * @param format
 *            日期格式字符串
 * @return String 指定格式的日期字符串.
 */
public static String getFormatDateTime(Date date, String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    return sdf.format(date);
}

/**
 * 取得指定年月日的日期對象.
 *
 * @param year
 *            年
 * @param month
 *            月注意是從1到12
 * @param day
 *            日
 * @return 一個java.util.Date()類型的對象
 */
public static Date getDateObj(int year, int month, int day) {
    Calendar c = new GregorianCalendar();
    c.set(year, month - 1, day);
    return c.getTime();
}

/**
 * 獲取指定日期的下一天。
 *
 * @param date
 *            yyyy/MM/dd
 * @return yyyy/MM/dd
 */
public static String getDateTomorrow(String date) {

    Date tempDate = null;
    if (date.indexOf("/") > 0)
        tempDate = getDateObj(date, "[/]");
    if (date.indexOf("-") > 0)
        tempDate = getDateObj(date, "[-]");
    tempDate = getDateAdd(tempDate, 1);
    return getFormatDateTime(tempDate, "yyyy/MM/dd");
}

/**
 * 獲取與指定日期相差指定天數的日期。
 *
 * @param date
 *            yyyy/MM/dd
 * @param offset
 *            正整數
 * @return yyyy/MM/dd
 */
public static String getDateOffset(String date, int offset) {

    // Date tempDate = getDateObj(date, "[/]");
    Date tempDate = null;
    if (date.indexOf("/") > 0)
        tempDate = getDateObj(date, "[/]");
    if (date.indexOf("-") > 0)
        tempDate = getDateObj(date, "[-]");
    tempDate = getDateAdd(tempDate, offset);
    return getFormatDateTime(tempDate, "yyyy/MM/dd");
}

/**
 * 取得指定分隔符分割的年月日的日期對象.
 *
 * @param argsDate
 *            格式為"yyyy-MM-dd"
 * @param split
 *            時間格式的間隔符,例如“-”,“/”,要和時間一致起來。
 * @return 一個java.util.Date()類型的對象
 */
public static Date getDateObj(String argsDate, String split) {
    String[] temp = argsDate.split(split);
    int year = new Integer(temp[0]).intValue();
    int month = new Integer(temp[1]).intValue();
    int day = new Integer(temp[2]).intValue();
    return getDateObj(year, month, day);
}

/**
 * 取得給定字符串描述的日期對象,描述模式采用pattern指定的格式.
 *
 * @param dateStr
 *            日期描述 從給定字符串的開始分析文本,以生成一個日期。該方法不使用給定字符串的整個文本。 有關日期分析的更多信息,請參閱
 *            parse(String, ParsePosition) 方法。一個 String,應從其開始處進行分析
 *
 * @param pattern
 *            日期模式
 * @return 給定字符串描述的日期對象。
 */
public static Date getDateFromString(String dateStr, String pattern) {
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    Date resDate = null;
    try {
        resDate = sdf.parse(dateStr);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resDate;
}

/**
 * 取得當前Date對象.
 *
 * @return Date 當前Date對象.
 */
public static Date getDateObj() {
    Calendar c = new GregorianCalendar();
    return c.getTime();
}

/**
 *
 * @return 當前月份有多少天;
 */
public static int getDaysOfCurMonth() {
    int curyear = new Integer(getCurrentYear()).intValue(); // 當前年份
    int curMonth = new Integer(getCurrentMonth()).intValue();// 當前月份
    int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
            31 };
    // 判斷閏年的情況 ,2月份有29天;
    if ((curyear % 400 == 0)
            || ((curyear % 100 != 0) && (curyear % 4 == 0))) {
        mArray[1] = 29;
    }
    return mArray[curMonth - 1];
    // 如果要返回下個月的天數,注意處理月份12的情況,防止數組越界;
    // 如果要返回上個月的天數,注意處理月份1的情況,防止數組越界;
}

/**
 * 根據指定的年月 返回指定月份(yyyy-MM)有多少天。
 *
 * @param time
 *            yyyy-MM
 * @return 天數,指定月份的天數。
 */
public static int getDaysOfCurMonth(final String time) {
    if (time.length() != 7) {
        throw new NullPointerException("參數的格式必須是yyyy-MM");
    }
    String[] timeArray = time.split("-");
    int curyear = new Integer(timeArray[0]).intValue(); // 當前年份
    int curMonth = new Integer(timeArray[1]).intValue();// 當前月份
    if (curMonth > 12) {
        throw new NullPointerException("參數的格式必須是yyyy-MM,而且月份必須小于等于12。");
    }
    int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
            31 };
    // 判斷閏年的情況 ,2月份有29天;
    if ((curyear % 400 == 0)
            || ((curyear % 100 != 0) && (curyear % 4 == 0))) {
        mArray[1] = 29;
    }
    if (curMonth == 12) {
        return mArray[0];
    }
    return mArray[curMonth - 1];
    // 如果要返回下個月的天數,注意處理月份12的情況,防止數組越界;
    // 如果要返回上個月的天數,注意處理月份1的情況,防止數組越界;
}

/**
 * 返回指定為年度為year月度month的月份內,第weekOfMonth個星期的第dayOfWeek天是當月的幾號。<br>
 * 00 00 00 01 02 03 04 <br>
 * 05 06 07 08 09 10 11<br>
 * 12 13 14 15 16 17 18<br>
 * 19 20 21 22 23 24 25<br>
 * 26 27 28 29 30 31 <br>
 * 2006年的第一個周的1到7天為:05 06 07 01 02 03 04 <br>
 * 2006年的第二個周的1到7天為:12 13 14 08 09 10 11 <br>
 * 2006年的第三個周的1到7天為:19 20 21 15 16 17 18 <br>
 * 2006年的第四個周的1到7天為:26 27 28 22 23 24 25 <br>
 * 2006年的第五個周的1到7天為:02 03 04 29 30 31 01 。本月沒有就自動轉到下個月了。
 *
 * @param year
 *            形式為yyyy <br>
 * @param month
 *            形式為MM,參數值在[1-12]。<br>
 * @param weekOfMonth
 *            在[1-6],因為一個月最多有6個周。<br>
 * @param dayOfWeek
 *            數字在1到7之間,包括1和7。1表示星期天,7表示星期六<br>
 *            -6為星期日-1為星期五,0為星期六 <br>
 * @return <type>int</type>
 */
public static int getDayofWeekInMonth(String year, String month,
        String weekOfMonth, String dayOfWeek) {
    Calendar cal = new GregorianCalendar();
    // 在具有默認語言環境的默認時區內使用當前時間構造一個默認的 GregorianCalendar。
    int y = new Integer(year).intValue();
    int m = new Integer(month).intValue();
    cal.clear();// 不保留以前的設置
    cal.set(y, m - 1, 1);// 將日期設置為本月的第一天。
    cal.set(Calendar.DAY_OF_WEEK_IN_MONTH,
            new Integer(weekOfMonth).intValue());
    cal.set(Calendar.DAY_OF_WEEK, new Integer(dayOfWeek).intValue());
    // System.out.print(cal.get(Calendar.MONTH)+" ");
    // System.out.print("當"+cal.get(Calendar.WEEK_OF_MONTH)+"\t");
    // WEEK_OF_MONTH表示當天在本月的第幾個周。不管1號是星期幾,都表示在本月的第一個周
    return cal.get(Calendar.DAY_OF_MONTH);
}

/**
 * 根據指定的年月日小時分秒,返回一個java.Util.Date對象。
 *
 * @param year
 *            年
 * @param month
 *            月 0-11
 * @param date
 *            日
 * @param hourOfDay
 *            小時 0-23
 * @param minute
 *            分 0-59
 * @param second
 *            秒 0-59
 * @return 一個Date對象。
 */
public static Date getDate(int year, int month, int date, int hourOfDay,
        int minute, int second) {
    Calendar cal = new GregorianCalendar();
    cal.set(year, month, date, hourOfDay, minute, second);
    return cal.getTime();
}

/**
 * 根據指定的年、月、日返回當前是星期幾。1表示星期天、2表示星期一、7表示星期六。
 *
 * @param year
 * @param month
 *            month是從1開始的12結束
 * @param day
 * @return 返回一個代表當期日期是星期幾的數字。1表示星期天、2表示星期一、7表示星期六。
 */
public static int getDayOfWeek(String year, String month, String day) {
    Calendar cal = new GregorianCalendar(new Integer(year).intValue(),
            new Integer(month).intValue() - 1, new Integer(day).intValue());
    return cal.get(Calendar.DAY_OF_WEEK);
}

/**
 * 根據指定的年、月、日返回當前是星期幾。1表示星期天、2表示星期一、7表示星期六。
 *
 * @param date
 *            "yyyy/MM/dd",或者"yyyy-MM-dd"
 * @return 返回一個代表當期日期是星期幾的數字。1表示星期天、2表示星期一、7表示星期六。
 */
public static int getDayOfWeek(String date) {
    String[] temp = null;
    if (date.indexOf("/") > 0) {
        temp = date.split("/");
    }
    if (date.indexOf("-") > 0) {
        temp = date.split("-");
    }
    return getDayOfWeek(temp[0], temp[1], temp[2]);
}

/**
 * 返回當前日期是星期幾。例如:星期日、星期一、星期六等等。
 *
 * @param date
 *            格式為 yyyy/MM/dd 或者 yyyy-MM-dd
 * @return 返回當前日期是星期幾
 */
public static String getChinaDayOfWeek(String date) {
    String[] weeks = new String[] { "星期日", "星期一", "星期二", "星期三", "星期四",
            "星期五", "星期六" };
    int week = getDayOfWeek(date);
    return weeks[week - 1];
}

/**
 * 根據指定的年、月、日返回當前是星期幾。1表示星期天、2表示星期一、7表示星期六。
 *
 * @param date
 *
 * @return 返回一個代表當期日期是星期幾的數字。1表示星期天、2表示星期一、7表示星期六。
 */
public static int getDayOfWeek(Date date) {
    Calendar cal = new GregorianCalendar();
    cal.setTime(date);
    return cal.get(Calendar.DAY_OF_WEEK);
}

/**
 * 返回制定日期所在的周是一年中的第幾個周
 * created by wangmj at 20060324.<br>
 *
 * @param year
 * @param month
 *            范圍1-12<br>
 * @param day
 * @return int
 */
public static int getWeekOfYear(String year, String month, String day) {
    Calendar cal = new GregorianCalendar();
    cal.clear();
    cal.set(new Integer(year).intValue(),
            new Integer(month).intValue() - 1, new Integer(day).intValue());
    return cal.get(Calendar.WEEK_OF_YEAR);
}

/**
 * 取得給定日期加上一定天數后的日期對象.
 *
 * @param date
 *            給定的日期對象
 * @param amount
 *            需要添加的天數,如果是向前的天數,使用負數就可以.
 * @return Date 加上一定天數以后的Date對象.
 */
public static Date getDateAdd(Date date, int amount) {
    Calendar cal = new GregorianCalendar();
    cal.setTime(date);
    cal.add(GregorianCalendar.DATE, amount);
    return cal.getTime();
}

/**
 * 取得給定日期加上一定天數后的日期對象.
 *
 * @param date
 *            給定的日期對象
 * @param amount
 *            需要添加的天數,如果是向前的天數,使用負數就可以.
 * @param format
 *            輸出格式.
 * @return Date 加上一定天數以后的Date對象.
 */
public static String getFormatDateAdd(Date date, int amount, String format) {
    Calendar cal = new GregorianCalendar();
    cal.setTime(date);
    cal.add(GregorianCalendar.DATE, amount);
    return getFormatDateTime(cal.getTime(), format);
}

/**
 * 獲得當前日期固定間隔天數的日期,如前60天dateAdd(-60)
 *
 * @param amount
 *            距今天的間隔日期長度,向前為負,向后為正
 * @param format
 *            輸出日期的格式.
 * @return java.lang.String 按照格式輸出的間隔的日期字符串.
 */
public static String getFormatCurrentAdd(int amount, String format) {

    Date d = getDateAdd(new Date(), amount);

    return getFormatDateTime(d, format);
}

/**
 * 取得給定格式的昨天的日期輸出
 *
 * @param format
 *            日期輸出的格式
 * @return String 給定格式的日期字符串.
 */
public static String getFormatYestoday(String format) {
    return getFormatCurrentAdd(-1, format);
}

/**
 * 返回指定日期的前一天。<br>
 *
 * @param sourceDate
 * @param format
 *            yyyy MM dd hh mm ss
 * @return 返回日期字符串,形式和formcat一致。
 */
public static String getYestoday(String sourceDate, String format) {
    return getFormatDateAdd(getDateFromString(sourceDate, format), -1,
            format);
}

/**
 * 返回明天的日期,<br>
 *
 * @param format
 * @return 返回日期字符串,形式和formcat一致。
 */
public static String getFormatTomorrow(String format) {
    return getFormatCurrentAdd(1, format);
}

/**
 * 返回指定日期的后一天。<br>
 *
 * @param sourceDate
 * @param format
 * @return 返回日期字符串,形式和formcat一致。
 */
public static String getFormatDateTommorrow(String sourceDate, String format) {
    return getFormatDateAdd(getDateFromString(sourceDate, format), 1,
            format);
}

/**
 * 根據主機的默認 TimeZone,來獲得指定形式的時間字符串。
 *
 * @param dateFormat
 * @return 返回日期字符串,形式和formcat一致。
 */
public static String getCurrentDateString(String dateFormat) {
    Calendar cal = Calendar.getInstance(TimeZone.getDefault());
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    sdf.setTimeZone(TimeZone.getDefault());

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

// /**
// * @deprecated 不鼓勵使用。 返回當前時間串 格式:yyMMddhhmmss,在上傳附件時使用
// *
// * @return String
// */
// public static String getCurDate() {
// GregorianCalendar gcDate = new GregorianCalendar();
// int year = gcDate.get(GregorianCalendar.YEAR);
// int month = gcDate.get(GregorianCalendar.MONTH) + 1;
// int day = gcDate.get(GregorianCalendar.DAY_OF_MONTH);
// int hour = gcDate.get(GregorianCalendar.HOUR_OF_DAY);
// int minute = gcDate.get(GregorianCalendar.MINUTE);
// int sen = gcDate.get(GregorianCalendar.SECOND);
// String y;
// String m;
// String d;
// String h;
// String n;
// String s;
// y = new Integer(year).toString();
//
// if (month < 10) {
// m = "0" + new Integer(month).toString();
// } else {
// m = new Integer(month).toString();
// }
//
// if (day < 10) {
// d = "0" + new Integer(day).toString();
// } else {
// d = new Integer(day).toString();
// }
//
// if (hour < 10) {
// h = "0" + new Integer(hour).toString();
// } else {
// h = new Integer(hour).toString();
// }
//
// if (minute < 10) {
// n = "0" + new Integer(minute).toString();
// } else {
// n = new Integer(minute).toString();
// }
//
// if (sen < 10) {
// s = "0" + new Integer(sen).toString();
// } else {
// s = new Integer(sen).toString();
// }
//
// return "" + y + m + d + h + n + s;
// }

/**
 * 根據給定的格式,返回時間字符串。 和getFormatDate(String format)相似。
 *
 * @param format
 *            yyyy MM dd hh mm ss
 * @return 返回一個時間字符串
 */
public static String getCurTimeByFormat(String format) {
    Date newdate = new Date(System.currentTimeMillis());
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    return sdf.format(newdate);
}

/**
 * 獲取兩個時間串時間的差值,單位為秒
 *
 * @param startTime
 *            開始時間 yyyy-MM-dd HH:mm:ss
 * @param endTime
 *            結束時間 yyyy-MM-dd HH:mm:ss
 * @return 兩個時間的差值(秒)
 */
public static long getDiff(String startTime, String endTime) {
    long diff = 0;
    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date startDate = ft.parse(startTime);
        Date endDate = ft.parse(endTime);
        diff = startDate.getTime() - endDate.getTime();
        diff = diff / 1000;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return diff;
}

/**
 * 獲取小時/分鐘/秒
 *
 * @param second
 *            秒
 * @return 包含小時、分鐘、秒的時間字符串,例如3小時23分鐘13秒。
 */
public static String getHour(long second) {
    long hour = second / 60 / 60;
    long minute = (second - hour * 60 * 60) / 60;
    long sec = (second - hour * 60 * 60) - minute * 60;

    return hour + "小時" + minute + "分鐘" + sec + "秒";

}

/**
 * 返回指定時間字符串。
 * <p>
 * 格式:yyyy-MM-dd HH:mm:ss
 *
 * @return String 指定格式的日期字符串.
 */
public static String getDateTime(long microsecond) {
    return getFormatDateTime(new Date(microsecond), "yyyy-MM-dd HH:mm:ss");
}

/**
 * 返回當前時間加實數小時后的日期時間。
 * <p>
 * 格式:yyyy-MM-dd HH:mm:ss
 *
 * @return Float 加幾實數小時.
 */
public static String getDateByAddFltHour(float flt) {
    int addMinute = (int) (flt * 60);
    Calendar cal = new GregorianCalendar();
    cal.setTime(new Date());
    cal.add(GregorianCalendar.MINUTE, addMinute);
    return getFormatDateTime(cal.getTime(), "yyyy-MM-dd HH:mm:ss");
}

/**
 * 返回指定時間加指定小時數后的日期時間。
 * <p>
 * 格式:yyyy-MM-dd HH:mm:ss
 *
 * @return 時間.
 */
public static String getDateByAddHour(String datetime, int minute) {
    String returnTime = null;
    Calendar cal = new GregorianCalendar();
    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date;
    try {
        date = ft.parse(datetime);
        cal.setTime(date);
        cal.add(GregorianCalendar.MINUTE, minute);
        returnTime = getFormatDateTime(cal.getTime(), "yyyy-MM-dd HH:mm:ss");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return returnTime;

}

/**
 * 獲取兩個時間串時間的差值,單位為小時
 *
 * @param startTime
 *            開始時間 yyyy-MM-dd HH:mm:ss
 * @param endTime
 *            結束時間 yyyy-MM-dd HH:mm:ss
 * @return 兩個時間的差值(秒)
 */
public static int getDiffHour(String startTime, String endTime) {
    long diff = 0;
    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date startDate = ft.parse(startTime);
        Date endDate = ft.parse(endTime);
        diff = startDate.getTime() - endDate.getTime();
        diff = diff / (1000 * 60 * 60);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return new Long(diff).intValue();
}

/**
 * 返回年份的下拉框。
 *
 * @param selectName
 *            下拉框名稱
 * @param value
 *            當前下拉框的值
 * @param startYear
 *            開始年份
 * @param endYear
 *            結束年份
 * @return 年份下拉框的html
 */
public static String getYearSelect(String selectName, String value,
        int startYear, int endYear) {
    int start = startYear;
    int end = endYear;
    if (startYear > endYear) {
        start = endYear;
        end = startYear;
    }
    StringBuffer sb = new StringBuffer("");
    sb.append("<select name=\"" + selectName + "\">");
    for (int i = start; i <= end; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 返回年份的下拉框。
 *
 * @param selectName
 *            下拉框名稱
 * @param value
 *            當前下拉框的值
 * @param startYear
 *            開始年份
 * @param endYear
 *            結束年份
 *            例如開始年份為2001結束年份為2005那么下拉框就有五個值。(2001、2002、2003、2004、2005)。
 * @return 返回年份的下拉框的html。
 */
public static String getYearSelect(String selectName, String value,
        int startYear, int endYear, boolean hasBlank) {
    int start = startYear;
    int end = endYear;
    if (startYear > endYear) {
        start = endYear;
        end = startYear;
    }
    StringBuffer sb = new StringBuffer("");
    sb.append("<select name=\"" + selectName + "\">");
    if (hasBlank) {
        sb.append("<option value=\"\"></option>");
    }
    for (int i = start; i <= end; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 返回年份的下拉框。
 *
 * @param selectName
 *            下拉框名稱
 * @param value
 *            當前下拉框的值
 * @param startYear
 *            開始年份
 * @param endYear
 *            結束年份
 * @param js
 *            這里的js為js字符串。例如 " onchange=\"changeYear()\" "
 *            ,這樣任何js的方法就可以在jsp頁面中編寫,方便引入。
 * @return 返回年份的下拉框。
 */
public static String getYearSelect(String selectName, String value,
        int startYear, int endYear, boolean hasBlank, String js) {
    int start = startYear;
    int end = endYear;
    if (startYear > endYear) {
        start = endYear;
        end = startYear;
    }
    StringBuffer sb = new StringBuffer("");

    sb.append("<select name=\"" + selectName + "\" " + js + ">");
    if (hasBlank) {
        sb.append("<option value=\"\"></option>");
    }
    for (int i = start; i <= end; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 返回年份的下拉框。
 *
 * @param selectName
 *            下拉框名稱
 * @param value
 *            當前下拉框的值
 * @param startYear
 *            開始年份
 * @param endYear
 *            結束年份
 * @param js
 *            這里的js為js字符串。例如 " onchange=\"changeYear()\" "
 *            ,這樣任何js的方法就可以在jsp頁面中編寫,方便引入。
 * @return 返回年份的下拉框。
 */
public static String getYearSelect(String selectName, String value,
        int startYear, int endYear, String js) {
    int start = startYear;
    int end = endYear;
    if (startYear > endYear) {
        start = endYear;
        end = startYear;
    }
    StringBuffer sb = new StringBuffer("");
    sb.append("<select name=\"" + selectName + "\" " + js + ">");
    for (int i = start; i <= end; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 獲取月份的下拉框
 *
 * @param selectName
 * @param value
 * @param hasBlank
 * @return 返回月份的下拉框。
 */
public static String getMonthSelect(String selectName, String value,
        boolean hasBlank) {
    StringBuffer sb = new StringBuffer("");
    sb.append("<select name=\"" + selectName + "\">");
    if (hasBlank) {
        sb.append("<option value=\"\"></option>");
    }
    for (int i = 1; i <= 12; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 獲取月份的下拉框
 *
 * @param selectName
 * @param value
 * @param hasBlank
 * @param js
 * @return 返回月份的下拉框。
 */
public static String getMonthSelect(String selectName, String value,
        boolean hasBlank, String js) {
    StringBuffer sb = new StringBuffer("");
    sb.append("<select name=\"" + selectName + "\" " + js + ">");
    if (hasBlank) {
        sb.append("<option value=\"\"></option>");
    }
    for (int i = 1; i <= 12; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 獲取天的下拉框,默認的為1-31。 注意:此方法不能夠和月份下拉框進行聯動。
 *
 * @param selectName
 * @param value
 * @param hasBlank
 * @return 獲得天的下拉框
 */
public static String getDaySelect(String selectName, String value,
        boolean hasBlank) {
    StringBuffer sb = new StringBuffer("");
    sb.append("<select name=\"" + selectName + "\">");
    if (hasBlank) {
        sb.append("<option value=\"\"></option>");
    }
    for (int i = 1; i <= 31; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 獲取天的下拉框,默認的為1-31
 *
 * @param selectName
 * @param value
 * @param hasBlank
 * @param js
 * @return 獲取天的下拉框
 */
public static String getDaySelect(String selectName, String value,
        boolean hasBlank, String js) {
    StringBuffer sb = new StringBuffer("");
    sb.append("<select name=\"" + selectName + "\" " + js + ">");
    if (hasBlank) {
        sb.append("<option value=\"\"></option>");
    }
    for (int i = 1; i <= 31; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 計算兩天之間有多少個周末(這個周末,指星期六和星期天,一個周末返回結果為2,兩個為4,以此類推。) (此方法目前用于統計司機用車記錄。)
 * 注意開始日期和結束日期要統一起來。
 *
 * @param startDate
 *            開始日期 ,格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
 * @param endDate
 *            結束日期 ,格式"yyyy/MM/dd"或者"yyyy-MM-dd"
 * @return int
 */
public static int countWeekend(String startDate, String endDate) {
    int result = 0;
    Date sdate = null;
    Date edate = null;
    if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
        sdate = getDateObj(startDate, "/"); // 開始日期
        edate = getDateObj(endDate, "/");// 結束日期
    }
    if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
        sdate = getDateObj(startDate, "-"); // 開始日期
        edate = getDateObj(endDate, "-");// 結束日期
    }

    // 首先計算出都有那些日期,然后找出星期六星期天的日期
    int sumDays = Math.abs(getDiffDays(startDate, endDate));
    int dayOfWeek = 0;
    for (int i = 0; i <= sumDays; i++) {
        dayOfWeek = getDayOfWeek(getDateAdd(sdate, i)); // 計算每過一天的日期
        if (dayOfWeek == 1 || dayOfWeek == 7) { // 1 星期天 7星期六
            result++;
        }
    }
    return result;
}

/**
 * 返回兩個日期之間相差多少天。 注意開始日期和結束日期要統一起來。
 *
 * @param startDate
 *            格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
 * @param endDate
 *            格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
 * @return 整數。
 */
public static int getDiffDays(String startDate, String endDate) {
    long diff = 0;
    SimpleDateFormat ft = null;
    if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
        ft = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    }
    if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
        ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
    try {
        Date sDate = ft.parse(startDate + " 00:00:00");
        Date eDate = ft.parse(endDate + " 00:00:00");
        diff = eDate.getTime() - sDate.getTime();
        diff = diff / 86400000;// 1000*60*60*24;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return (int) diff;

}

/**
 * 返回兩個日期之間的詳細日期數組(包括開始日期和結束日期)。 例如:2007/07/01 到2007/07/03 ,那么返回數組
 * {"2007/07/01","2007/07/02","2007/07/03"} 注意開始日期和結束日期要統一起來。
 *
 * @param startDate
 *            格式"yyyy/MM/dd"或者 yyyy-MM-dd
 * @param endDate
 *            格式"yyyy/MM/dd"或者 yyyy-MM-dd
 * @return 返回一個字符串數組對象
 */
public static String[] getArrayDiffDays(String startDate, String endDate) {
    int LEN = 0; // 用來計算兩天之間總共有多少天
    // 如果結束日期和開始日期相同
    if (startDate.equals(endDate)) {
        return new String[] { startDate };
    }
    Date sdate = null;
    if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
        sdate = getDateObj(startDate, "/"); // 開始日期
    }
    if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
        sdate = getDateObj(startDate, "-"); // 開始日期
    }

    LEN = getDiffDays(startDate, endDate);
    String[] dateResult = new String[LEN + 1];
    dateResult[0] = startDate;
    for (int i = 1; i < LEN + 1; i++) {
        if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
            dateResult[i] = getFormatDateTime(getDateAdd(sdate, i),
                    "yyyy/MM/dd");
        }
        if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
            dateResult[i] = getFormatDateTime(getDateAdd(sdate, i),
                    "yyyy-MM-dd");
        }
    }

    return dateResult;
}

/**
 * 判斷一個日期是否在開始日期和結束日期之間。
 *
 * @param srcDate
 *            目標日期 yyyy/MM/dd 或者 yyyy-MM-dd
 * @param startDate
 *            開始日期 yyyy/MM/dd 或者 yyyy-MM-dd
 * @param endDate
 *            結束日期 yyyy/MM/dd 或者 yyyy-MM-dd
 * @return 大于等于開始日期小于等于結束日期,那么返回true,否則返回false
 */
public static boolean isInStartEnd(String srcDate, String startDate,
        String endDate) {
    if (startDate.compareTo(srcDate) <= 0
            && endDate.compareTo(srcDate) >= 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * 獲取天的下拉框,默認的為1-4。 注意:此方法不能夠和月份下拉框進行聯動。
 *
 * @param selectName
 * @param value
 * @param hasBlank
 * @return 獲得季度的下拉框
 */
public static String getQuarterSelect(String selectName, String value,
        boolean hasBlank) {
    StringBuffer sb = new StringBuffer("");
    sb.append("<select name=\"" + selectName + "\">");
    if (hasBlank) {
        sb.append("<option value=\"\"></option>");
    }
    for (int i = 1; i <= 4; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 獲取季度的下拉框,默認的為1-4
 *
 * @param selectName
 * @param value
 * @param hasBlank
 * @param js
 * @return 獲取季度的下拉框
 */
public static String getQuarterSelect(String selectName, String value,
        boolean hasBlank, String js) {
    StringBuffer sb = new StringBuffer("");
    sb.append("<select name=\"" + selectName + "\" " + js + ">");
    if (hasBlank) {
        sb.append("<option value=\"\"></option>");
    }
    for (int i = 1; i <= 4; i++) {
        if (!value.trim().equals("") && i == Integer.parseInt(value)) {
            sb.append("<option value=\"" + i + "\" selected>" + i
                    + "</option>");
        } else {
            sb.append("<option value=\"" + i + "\">" + i + "</option>");
        }
    }
    sb.append("</select>");
    return sb.toString();
}

/**
 * 將格式為yyyy或者yyyy.MM或者yyyy.MM.dd的日期轉換為yyyy/MM/dd的格式。位數不足的,都補01。<br>
 * 例如.1999 = 1999/01/01 再如:1989.02=1989/02/01
 *
 * @param argDate
 *            需要進行轉換的日期。格式可能為yyyy或者yyyy.MM或者yyyy.MM.dd
 * @return 返回格式為yyyy/MM/dd的字符串
 */
public static String changeDate(String argDate) {
    if (argDate == null || argDate.trim().equals("")) {
        return "";
    }
    String result = "";
    // 如果是格式為yyyy/MM/dd的就直接返回
    if (argDate.length() == 10 && argDate.indexOf("/") > 0) {
        return argDate;
    }
    String[] str = argDate.split("[.]"); // .比較特殊
    int LEN = str.length;
    for (int i = 0; i < LEN; i++) {
        if (str[i].length() == 1) {
            if (str[i].equals("0")) {
                str[i] = "01";
            } else {
                str[i] = "0" + str[i];
            }
        }
    }
    if (LEN == 1) {
        result = argDate + "/01/01";
    }
    if (LEN == 2) {
        result = str[0] + "/" + str[1] + "/01";
    }
    if (LEN == 3) {
        result = str[0] + "/" + str[1] + "/" + str[2];
    }
    return result;
}

/**
 * 將格式為yyyy或者yyyy.MM或者yyyy.MM.dd的日期轉換為yyyy/MM/dd的格式。位數不足的,都補01。<br>
 * 例如.1999 = 1999/01/01 再如:1989.02=1989/02/01
 *
 * @param argDate
 *            需要進行轉換的日期。格式可能為yyyy或者yyyy.MM或者yyyy.MM.dd
 * @return 返回格式為yyyy/MM/dd的字符串
 */
public static String changeDateWithSplit(String argDate, String split) {
    if (argDate == null || argDate.trim().equals("")) {
        return "";
    }
    if (split == null || split.trim().equals("")) {
        split = "-";
    }
    String result = "";
    // 如果是格式為yyyy/MM/dd的就直接返回
    if (argDate.length() == 10 && argDate.indexOf("/") > 0) {
        return argDate;
    }
    // 如果是格式為yyyy-MM-dd的就直接返回
    if (argDate.length() == 10 && argDate.indexOf("-") > 0) {
        return argDate;
    }
    String[] str = argDate.split("[.]"); // .比較特殊
    int LEN = str.length;
    for (int i = 0; i < LEN; i++) {
        if (str[i].length() == 1) {
            if (str[i].equals("0")) {
                str[i] = "01";
            } else {
                str[i] = "0" + str[i];
            }
        }
    }
    if (LEN == 1) {
        result = argDate + split + "01" + split + "01";
    }
    if (LEN == 2) {
        result = str[0] + split + str[1] + split + "01";
    }
    if (LEN == 3) {
        result = str[0] + split + str[1] + split + str[2];
    }
    return result;
}

/**
 * 返回指定日期的的下一個月的天數。
 *
 * @param argDate
 *            格式為yyyy-MM-dd或者yyyy/MM/dd
 * @return 下一個月的天數。
 */
public static int getNextMonthDays(String argDate) {
    String[] temp = null;
    if (argDate.indexOf("/") > 0) {
        temp = argDate.split("/");
    }
    if (argDate.indexOf("-") > 0) {
        temp = argDate.split("-");
    }
    Calendar cal = new GregorianCalendar(new Integer(temp[0]).intValue(),
            new Integer(temp[1]).intValue() - 1,
            new Integer(temp[2]).intValue());
    int curMonth = cal.get(Calendar.MONTH);
    cal.set(Calendar.MONTH, curMonth + 1);

    int curyear = cal.get(Calendar.YEAR);// 當前年份
    curMonth = cal.get(Calendar.MONTH);// 當前月份,0-11

    int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
            31 };
    // 判斷閏年的情況 ,2月份有29天;
    if ((curyear % 400 == 0)
            || ((curyear % 100 != 0) && (curyear % 4 == 0))) {
        mArray[1] = 29;
    }
    return mArray[curMonth];
}

public static void main(String[] args) {
    System.out.println(DateTools.getCurrentDateTime());
    System.out.println("first=" + changeDateWithSplit("2000.1", ""));
    System.out.println("second=" + changeDateWithSplit("2000.1", "/"));
    String[] t = getArrayDiffDays("2008/02/15", "2008/02/19");
    for (int i = 0; i < t.length; i++) {
        System.out.println(t[i]);
    }
    t = getArrayDiffDays("2008-02-15", "2008-02-19");
    for (int i = 0; i < t.length; i++) {
        System.out.println(t[i]);
    }
    System.out.println(getNextMonthDays("2008/02/15") + "||"
            + getCurrentMonth() + "||" + DateTools.changeDate("1999"));
    System.out.println(DateTools.changeDate("1999.1"));
    System.out.println(DateTools.changeDate("1999.11"));
    System.out.println(DateTools.changeDate("1999.1.2"));
    System.out.println(DateTools.changeDate("1999.11.12"));
}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!