DIV CSS 佈局教程網

Java 日期處理大全:格式化、週月季度與間隔天數計算
編輯:關於JavaScript     

日期計算瑣碎又容易出錯:上週一、上月末、本季度範圍、兩個日期相差幾天……下面把常用操作整理成一個可直接複用的工具類。

一、最基礎的互轉

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.getSaturday());
  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){
        }
        c.setTime(date);//設置日歷時間
        c.add(Calendar.MONTH,month);//在日歷的月份上增加指定月數
        String strDate = sdf.format(c.getTime());//得到想要的日期
        return strDate;
}

四、日期間隔與星期推算

/**
 * 得到兩個日期間的間隔天數
*/
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
*/
public static Date strToDate(String strDate) {
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  ParsePosition pos = new ParsePosition(0);
  Date strtodate = formatter.parse(strDate, pos);
  return strtodate;
}

/**
 * 兩個時間之間的天數
*/
public static long getDays(String date1, String date2) {
  if (date1 == null || date1.equals("")) return 0;
  if (date2 == null || date2.equals("")) return 0;
  SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
  java.util.Date date = null;
  java.util.Date mydate = null;
  try {
    date = myFormatter.parse(date1);
    mydate = myFormatter.parse(date2);
  } catch (Exception e) {
  }
  long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
  return day;
}

提示:用毫秒差除以一天的毫秒數時,若跨越夏令時會有偏差;更穩妥的做法是使用 ChronoUnit.DAYS.between()。

五、當月與上月的邊界日期

核心技巧只有一個套路:先把日期設為本月 1 號,再 add 一個月,最後回滾一天,就得到當月的最後一天。

// 計算當月最後一天
public String getDefaultDay(){
  String str = "";
  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);//減去一天,變為當月最後一天
  str=sdf.format(lastDate.getTime());
  return str;
}

// 上月第一天
public String getPreviousMonthFirst(){
  String str = "";
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  Calendar lastDate = Calendar.getInstance();
  lastDate.set(Calendar.DATE,1);//設為當前月的1號
  lastDate.add(Calendar.MONTH,-1);//減一個月
  str=sdf.format(lastDate.getTime());
  return str;
}

// 獲取當月第一天
public String getFirstDayOfMonth(){
  String str = "";
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  Calendar lastDate = Calendar.getInstance();
  lastDate.set(Calendar.DATE,1);//設為當前月的1號
  str=sdf.format(lastDate.getTime());
  return str;
}

// 獲得上月最後一天的日期
public String getPreviousMonthEnd(){
  String str = "";
  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);//日期回滾一天,即上月最後一天
  str=sdf.format(lastDate.getTime());
  return str;
}

// 獲得下個月第一天的日期
public String getNextMonthFirst(){
  String str = "";
  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
  Calendar lastDate = Calendar.getInstance();
  lastDate.add(Calendar.MONTH,1);//加一個月
  lastDate.set(Calendar.DATE, 1);//把日期設置為當月第一天
  str=sdf.format(lastDate.getTime());
  return str;
}

// 獲得下個月最後一天的日期
public String getNextMonthEnd(){
  String str = "";
  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);//日期回滾一天
  str=sdf.format(lastDate.getTime());
  return str;
}

另外兩個輔助方法 getMonthPlus() 與 getMaxYear() 分別用類似手法算出「本月/本年最大天數」與「當天距月初/年初的偏移」,供後續週年計算使用。

六、本周、上周、下周的邊界

這組方法都依賴 weeks 變量做周偏移,並用 getMondayPlus() 算出「今天與本週一相差的天數」。

// 獲得當前日期與本周一相差的天數
private int getMondayPlus() {
  Calendar cd = Calendar.getInstance();
  // 獲得今天是一周的第幾天,星期日為第一天
  int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK)-1; //按中國禮拜一作為第一天,所以減1
  if (dayOfWeek == 1) {
    return 0;
  } else {
    return 1 - dayOfWeek;
  }
}

// 獲得本周星期日的日期
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();
  SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);//可以方便地修改日期格式
  return dateFormat.format(now);
}

// 獲得本周一的日期
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();
  DateFormat df = DateFormat.getDateInstance();
  return df.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();
  DateFormat df = DateFormat.getDateInstance();
  return df.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();
  DateFormat df = DateFormat.getDateInstance();
  return df.format(monday);
}

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

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

注意:weeks 是成員變量且方法會修改它,所以這些方法不是線程安全的,也不建議反覆調用;實戰中更推薦把 weeks 作為參數顯式傳入。

七、本年、去年的邊界

// 獲得明年最後一天的日期
public String getNextYearEnd(){
  String str = "";
  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);
  str=sdf.format(lastDate.getTime());
  return str;
}

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

// 獲得本年有多少天
private int getMaxYear(){
  Calendar cd = Calendar.getInstance();
  cd.set(Calendar.DAY_OF_YEAR,1);//把日期設為當年第一天
  cd.roll(Calendar.DAY_OF_YEAR,-1);//把日期回滾一天
  int MaxYear = cd.get(Calendar.DAY_OF_YEAR);
  return MaxYear;
}

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

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

// 獲得上年第一天的日期
public String getPreviousYearFirst(){
  Date date = new Date();
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
  String years = dateFormat.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();
  DateFormat df = DateFormat.getDateInstance();
  return df.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();
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
  String years = dateFormat.format(date);
  int years_value = Integer.parseInt(years);
  int start_days = 1;
  int end_days = getLastDayOfMonth(years_value,end_month);
  String seasonDate = years_value+"-"+start_month+"-"+start_days+";"+years_value+"-"+end_month+"-"+end_days;
  return seasonDate;
}

九、月末天數與閏年判斷

/**
 * 獲取某年某月的最後一天
*/
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) {
    if (isLeapYear(year)) {
      return 29;
    } else {
      return 28;
    }
  }
  return 0;
}

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

十、現代寫法對照(強烈推薦)

上面這套代碼基於 Calendar/GregorianCalendar,寫法冗長且線程不安全(SimpleDateFormat 是共享狀態的大敵)。Java 8 之後的 java.time API 能把同樣的需求寫得短得多:

LocalDate today = LocalDate.now();
today.plusMonths(6); // 六個月後
today.with(TemporalAdjusters.firstDayOfMonth()); // 本月第一天
today.with(TemporalAdjusters.lastDayOfMonth()); // 本月最後一天
today.minusMonths(1).with(TemporalAdjusters.firstDayOfMonth()); // 上月第一天
today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)); // 本週一
today.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)); // 下週日
ChronoUnit.DAYS.between(d1, d2); // 相差天數
YearMonth.now().lengthOfMonth(); // 當月天數
LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // 格式化

新項目請直接使用 java.time:類型不可變、線程安全、月份與星期運算語義清晰,也不再有 1900 年偏移和 0 起始月份這類歷史包袱。

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