DIV CSS 佈局教程網

Java 獲取指定日期的方法總結:各類常用日期計算
編輯:JavaScript綜合知識     

日期處理是業務開發中的高頻需求:取前後幾個月、算本周一、求季度起止、判斷閏年。Java 的 Calendar 與 SimpleDateFormat 能覆蓋這些場景,下面把常用操作整理成一份可直接複用的工具類。

基礎:字符串與 Date 互轉

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Date date  = sdf.parse("2009-11-04"); // String --> Date
String sdate = sdf.format(date);      // Date  --> String

工具類主體

package com.hefeng.test;

import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class TimeTest {

  // 全局控制上一周、本周、下一周的周數偏移
  private int weeks = 0;
  private int MaxDate;  // 一月最大天數
  private int MaxYear;  // 一年最大天數

  public static void main(String[] args) {
    TimeTest tt = new TimeTest();

    System.out.println("得到6個月後的日期:" + tt.getAfterMonth(6));
    System.out.println("獲取當天日期:" + tt.getNowTime("yyyy-MM-dd"));
    System.out.println("獲取本周一日期:" + tt.getMondayOFWeek());
    System.out.println("獲取本周日的日期:" + tt.getCurrentWeekday());
    System.out.println("獲取上周一日期:" + tt.getPreviousWeekday());
    System.out.println("獲取上周日日期:" + tt.getPreviousWeekSunday());
    System.out.println("獲取下周一日期:" + tt.getNextMonday());
    System.out.println("獲取下周日日期:" + tt.getNextSunday());
    System.out.println("獲取本月第一天日期:" + tt.getFirstDayOfMonth());
    System.out.println("獲取本月最後一天日期:" + tt.getDefaultDay());
    System.out.println("獲取上月第一天日期:" + tt.getPreviousMonthFirst());
    System.out.println("獲取上月最後一天的日期:" + tt.getPreviousMonthEnd());
    System.out.println("獲取下月第一天日期:" + tt.getNextMonthFirst());
    System.out.println("獲取下月最後一天日期:" + tt.getNextMonthEnd());
    System.out.println("獲取本年的第一天日期:" + tt.getCurrentYearFirst());
    System.out.println("獲取本年最後一天日期:" + tt.getCurrentYearEnd());
    System.out.println("獲取去年的第一天日期:" + tt.getPreviousYearFirst());
    System.out.println("獲取去年的最後一天日期:" + tt.getPreviousYearEnd());
    System.out.println("獲取明年第一天日期:" + tt.getNextYearFirst());
    System.out.println("獲取明年最後一天日期:" + tt.getNextYearEnd());
    System.out.println("獲取本季度第一天到最後一天:" + tt.getThisSeasonTime(11));
    System.out.println("獲取兩個日期之間間隔天數:" + TimeTest.getTwoDay("2008-12-1", "2008-9-29"));
  }

  /** 得到指定月後(前)的日期,傳負數即可往前推 */
  public static String getAfterMonth(int month) {
    Calendar c = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
      date = sdf.parse("2009-11-04"); // 初始日期
    } catch (Exception e) {
      // 解析失敗時 date 保持為 null
    }
    c.setTime(date);
    c.add(Calendar.MONTH, month); // 在月份上做偏移
    return sdf.format(c.getTime());
  }

  /** 計算兩個日期之間的間隔天數 */
  public static String getTwoDay(String sj1, String sj2) {
    SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
    long day = 0;
    try {
      java.util.Date date   = myFormatter.parse(sj1);
      java.util.Date mydate = myFormatter.parse(sj2);
      day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
    } catch (Exception e) {
      return "";
    }
    return day + "";
  }

  /** 根據一個日期,返回星期幾的字符串 */
  public static String getWeek(String sdate) {
    Date date = TimeTest.strToDate(sdate);
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    // c.get(Calendar.DAY_OF_WEEK) 返回 1~7,1=星期日,7=星期六
    return new SimpleDateFormat("EEEE").format(c.getTime());
  }

  /** 將 "yyyy-MM-dd" 格式的字符串轉為 Date */
  public static Date strToDate(String strDate) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    ParsePosition pos = new ParsePosition(0);
    return formatter.parse(strDate, pos);
  }

  /** 計算當月最後一天 */
  public String getDefaultDay() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar lastDate = Calendar.getInstance();
    lastDate.set(Calendar.DATE, 1);   // 設為當月 1 號
    lastDate.add(Calendar.MONTH, 1);  // 加一個月,到下月 1 號
    lastDate.add(Calendar.DATE, -1);  // 減一天,回到當月最後一天
    return sdf.format(lastDate.getTime());
  }

  /** 上月第一天 */
  public String getPreviousMonthFirst() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar lastDate = Calendar.getInstance();
    lastDate.set(Calendar.DATE, 1);
    lastDate.add(Calendar.MONTH, -1);
    return sdf.format(lastDate.getTime());
  }

  /** 當月第一天 */
  public String getFirstDayOfMonth() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar lastDate = Calendar.getInstance();
    lastDate.set(Calendar.DATE, 1);
    return sdf.format(lastDate.getTime());
  }

  /** 獲得本周星期日的日期 */
  public String getCurrentWeekday() {
    weeks = 0;
    int mondayPlus = this.getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 6);
    Date monday = currentDate.getTime();
    DateFormat df = DateFormat.getDateInstance();
    return df.format(monday);
  }

  /** 獲取當前時間,格式可自定義 */
  public String getNowTime(String dateformat) {
    Date now = new Date();
    return new SimpleDateFormat(dateformat).format(now);
  }

  /** 當前日期與本周一相差的天數 */
  private int getMondayPlus() {
    Calendar cd = Calendar.getInstance();
    // 星期日是第一天,週期六是第七天;按中國習慣週一為第一天,故減 1
    int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;
    if (dayOfWeek == 1) {
      return 0;
    } else {
      return 1 - dayOfWeek;
    }
  }

  /** 獲得本周一的日期 */
  public String getMondayOFWeek() {
    weeks = 0;
    int mondayPlus = this.getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus);
    Date monday = currentDate.getTime();
    DateFormat df = DateFormat.getDateInstance();
    return df.format(monday);
  }

  /** 獲得相應周的周六 */
  public String getSaturday() {
    int mondayPlus = this.getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks + 6);
    Date monday = currentDate.getTime();
    return DateFormat.getDateInstance().format(monday);
  }

  /** 獲得上周星期日 */
  public String getPreviousWeekSunday() {
    weeks = 0;
    weeks--;
    int mondayPlus = this.getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + weeks);
    Date monday = currentDate.getTime();
    return DateFormat.getDateInstance().format(monday);
  }

  /** 獲得上周星期一 */
  public String getPreviousWeekday() {
    weeks--;
    int mondayPlus = this.getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
    Date monday = currentDate.getTime();
    return DateFormat.getDateInstance().format(monday);
  }

  /** 獲得下週星期一 */
  public String getNextMonday() {
    weeks++;
    int mondayPlus = this.getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 7);
    Date monday = currentDate.getTime();
    return DateFormat.getDateInstance().format(monday);
  }

  /** 獲得下週星期日 */
  public String getNextSunday() {
    int mondayPlus = this.getMondayPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 + 6);
    Date monday = currentDate.getTime();
    return DateFormat.getDateInstance().format(monday);
  }

  /** 獲得上月最後一天 */
  public String getPreviousMonthEnd() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar lastDate = Calendar.getInstance();
    lastDate.add(Calendar.MONTH, -1);
    lastDate.set(Calendar.DATE, 1);
    lastDate.roll(Calendar.DATE, -1); // 回滾一天,即上月最後一天
    return sdf.format(lastDate.getTime());
  }

  /** 獲得下個月第一天 */
  public String getNextMonthFirst() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar lastDate = Calendar.getInstance();
    lastDate.add(Calendar.MONTH, 1);
    lastDate.set(Calendar.DATE, 1);
    return sdf.format(lastDate.getTime());
  }

  /** 獲得下個月最後一天 */
  public String getNextMonthEnd() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar lastDate = Calendar.getInstance();
    lastDate.add(Calendar.MONTH, 1);
    lastDate.set(Calendar.DATE, 1);
    lastDate.roll(Calendar.DATE, -1);
    return sdf.format(lastDate.getTime());
  }

  /** 獲得明年第一天 */
  public String getNextYearFirst() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar lastDate = Calendar.getInstance();
    lastDate.add(Calendar.YEAR, 1);
    lastDate.set(Calendar.DAY_OF_YEAR, 1);
    return sdf.format(lastDate.getTime());
  }

  /** 獲得明年最後一天 */
  public String getNextYearEnd() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar lastDate = Calendar.getInstance();
    lastDate.add(Calendar.YEAR, 1);
    lastDate.set(Calendar.DAY_OF_YEAR, 1);
    lastDate.roll(Calendar.DAY_OF_YEAR, -1);
    return sdf.format(lastDate.getTime());
  }

  /** 獲得本年第一天 */
  public String getCurrentYearFirst() {
    int yearPlus = this.getYearPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, yearPlus);
    Date yearDay = currentDate.getTime();
    return DateFormat.getDateInstance().format(yearDay);
  }

  /** 獲得本年最後一天 */
  public String getCurrentYearEnd() {
    Date date = new Date();
    String years = new SimpleDateFormat("yyyy").format(date);
    return years + "-12-31";
  }

  /** 獲得上年第一天 */
  public String getPreviousYearFirst() {
    Date date = new Date();
    String years = new SimpleDateFormat("yyyy").format(date);
    int years_value = Integer.parseInt(years);
    years_value--;
    return years_value + "-1-1";
  }

  /** 獲得上年最後一天 */
  public String getPreviousYearEnd() {
    weeks--;
    int yearPlus = this.getYearPlus();
    GregorianCalendar currentDate = new GregorianCalendar();
    currentDate.add(GregorianCalendar.DATE, yearPlus + MaxYear * weeks + (MaxYear - 1));
    Date yearDay = currentDate.getTime();
    return DateFormat.getDateInstance().format(yearDay);
  }

  /** 獲得本季度的起止日期 */
  public String getThisSeasonTime(int month) {
    int array[][] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
    int season = 1;
    if (month >= 1  && month <= 3)  season = 1;
    if (month >= 4  && month <= 6)  season = 2;
    if (month >= 7  && month <= 9)  season = 3;
    if (month >= 10 && month <= 12) season = 4;

    int start_month = array[season - 1][0];
    int end_month   = array[season - 1][2];

    Date date = new Date();
    String years = new SimpleDateFormat("yyyy").format(date);
    int years_value = Integer.parseInt(years);

    int start_days = 1;
    int end_days = getLastDayOfMonth(years_value, end_month);

    return years_value + "-" + start_month + "-" + start_days + ";" +
           years_value + "-" + end_month + "-" + end_days;
  }

  /** 獲取某年某月的最後一天 */
  private int getLastDayOfMonth(int year, int month) {
    if (month == 1 || month == 3 || month == 5 || month == 7 ||
        month == 8 || month == 10 || month == 12) {
      return 31;
    }
    if (month == 4 || month == 6 || month == 9 || month == 11) {
      return 30;
    }
    if (month == 2) {
      return isLeapYear(year) ? 29 : 28;
    }
    return 0;
  }

  /** 判斷是否閏年 */
  public boolean isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
  }
}

關鍵技巧說明

整套代碼的核心套路只有兩個:Calendar.set() 把日期定位到某一基準點,然後用 Calendar.add() 做偏移。比如「本月最後一天」的求法是先設為 1 號避開月末天數不定的問題,加一個月到下月 1 號,再減一天回到本月月末。這個「歸一到 1 號再偏移」的思路能規避大量邊界 bug。

roll() 與 add() 的區別值得注意:add() 在跨單元時會引起連鎖進位(月加 1 可能導致年加 1),roll() 則只在當前單元內循環,不影響更大的單位。求月末天數時用 roll 更貼切。

閏年判斷遵循「四年一閏,百年不閏,四百年再閏」的規則,這也是 getLastDayOfMonth 能正確處理 2 月的依據。

這套代碼今天該如何改進

必須指出,這份工具類存在幾處需要修正的問題,以及在現代 Java 中更好的替代方案。

存在的方法依賴外部狀態。getPreviousWeekday()、getNextMonday() 等通過修改成員變量 weeks 來實現偏移,這導致方法不是純函數:連續調用兩次結果會不同,線程不安全,也难於組合。應改為顯式傳參,例如 getMondayOfWeek(int weekOffset)。

SimpleDateFormat 非線程安全。每次方法內部新建實例雖然規避了共享問題,但也帶來了不必要的對象開銷。更重要的是,將它作為靜態常量複用是多線程環境下的典型 bug 來源。

格式化結果依賴默認 Locale。DateFormat.getDateInstance() 在不同區域設置下輸出格式不同,導致 getMondayOFWeek() 等方法返回 "2013-12-16" 以外的格式,與方法名暗示的「日期」語義不符。應顯式指定 Locale 或使用固定 pattern。

日期差計算有夏令時隱患。用毫秒差除以一天的常量,在存在夏令時的時區會因 23 或 25 小時的一天而算錯。

現代替代方案:java.time。Java 8 引入的 LocalDate 把這些操作簡化到難以出錯的程度:

LocalDate today = LocalDate.now();

today.minusMonths(6);                          // 6 個月前
today.with(TemporalAdjusters.firstDayOfMonth());  // 本月第一天
today.with(TemporalAdjusters.lastDayOfMonth());   // 本月最后一天
today.with(DayOfWeek.MONDAY);                  // 本週一
today.minusWeeks(1).with(DayOfWeek.MONDAY);    // 上週一
today.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()); // 下月首日
ChronoUnit.DAYS.between(d1, d2);               // 間隔天數,無夏令時問題
today.getDayOfWeek();                          // 直接返回 DayOfWeek 枚舉
YearMonth.now().lengthOfMonth();               // 當月天數,自動處理閏年
today.format(DateTimeFormatter.ISO_LOCAL_DATE);// 格式化為字符串

LocalDate 及其同族類是不可變且線程安全的,TemporalAdjusters 提供了語義清晰的「本月第一天」「下季度首日」等調整器,ChronoUnit 基於日期而非毫秒計算時間差。上面數十行代碼在 java.time 下壓縮到幾行,且邊界情況由 JDK 保證正確。新項目請直接採用,舊代碼在升級時也可以逐個方法替換。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved