1. 程式人生 > >關於Calendar的一些用法總結

關於Calendar的一些用法總結

ger usm current tin array 其他 當前 boolean tex

import java.util.Calendar;

import java.security.KeyStore.TrustedCertificateEntry;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.ParsePosition;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.GregorianCalendar;

/**

* 常用日歷操作輔助類

*

*

*/

public class CalendarUtil {

// 用來全局控制 上一周,本周,下一周的周數變化

private int weeks = 0;

private int MaxDate;// 一月最大天數

private int MaxYear;// 一年最大天數

private static Calendar calendar = Calendar.getInstance();//實例化日歷

/**測試

* @param args

*/

public static void main(String[] args) {

CalendarUtil tt = new CalendarUtil();

System.out.println("獲取當天日期:" + tt.getNowTime("yyyy-MM-dd HH:mm:ss"));

//-------------------------------------------------------------

System.out.println("獲取本周一日期:" + tt.getMondayOFWeek());

System.out.println("獲取本周日的日期:" + tt.getSundayWeekday());

System.out.println("獲取上周日日期:" + tt.getPreviousWeekSunday());

System.out.println("獲取上周一日期:" + tt.getPreviousWeekday());

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("---------------->");

System.out.println("獲取當前月的第幾周:" + tt.getWeekOfMonth());

System.out.println("獲取當前年份:" + tt.getYear());

System.out.println("獲得本年有多少天:"+tt.getMaxYear());

System.out.println("獲取當前月份:" + tt.getMonth());

System.out.println("根據日期獲得當天周幾:" + tt.getWeek("2018-10-15"));

System.out.println("獲取今天在本年的第幾天:" + tt.getDayOfYear());

System.out.println("獲得今天在本月的第幾天(獲得當前日):" + tt.getDayOfMonth());

System.out.println("獲得今天在本周的第幾天:" + tt.getDayOfWeek());

System.out.println("獲取兩個日期之間間隔天數2018-5-1~2018-4-1:"

+ CalendarUtil.getTwoDay("2018-5-1", "2018-4-1"));

System.out.println("獲得半年後的日期:" + tt.convertDateToString(tt.getTimeYearNext()));

//-------------------------------------------------------------

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.getThisSeasonFirstTime());

//System.out.println("獲取本季度最後一天:" + tt.getThisSeasonFinallyTime());

//-------------------------------------------------------------

System.out.println("得到幾天前的日期:"+ tt.getDateBefore("2018-6-15", 20));

}

// 獲取當天時間

public String getNowTime(String dateformat) {//傳入參數為日期的格式

Date now = new Date();

SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);// 可以方便地修改日期格式

String toDay = dateFormat.format(now);

return toDay;

}

// 獲得本周一的日期

public String getMondayOFWeek() {

CalendarUtil tt = new CalendarUtil();

int mondayPlus =tt.getMondayPlus();//調用getMondayPlus方法獲得當前日期與本周一相差的天數

GregorianCalendar currentDate = new GregorianCalendar();

currentDate.add(GregorianCalendar.DATE, mondayPlus); //當天天數與相差的天數進行相加得到周一在本周的天數

Date monday = currentDate.getTime(); //根據天數獲得時間

DateFormat df = DateFormat.getDateInstance();

String preMonday = df.format(monday);

return preMonday;

}

// 獲得當前日期與本周一相差的天數

private int getMondayPlus() {

Calendar cd = Calendar.getInstance();

// 獲得今天是一周的第幾天,星期日是第一天,星期一是第二天......

int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; // 因為按中國禮拜一作為第一天所以這裏減1

if (dayOfWeek == 1) {

return 0; //如果是周一 返回0(無相差天數)

} else {

//返回與周一相差的天數(用以當天和相差天數計算)

//如果今天為周五 首先dayOfWeek == 5, 1-5則返回-4,當前減去4天就為周一的日期

return 1 - dayOfWeek;

}

}

// 獲得本周星期日的日期

public String getSundayWeekday() {

int mondayPlus = this.getMondayPlus();

GregorianCalendar currentDate = new GregorianCalendar();

currentDate.add(GregorianCalendar.DATE, mondayPlus + 6); //當天天數與相差的天數進行相加得到周日在本周的天數

Date monday = currentDate.getTime();

DateFormat df = DateFormat.getDateInstance();

String preMonday = df.format(monday);

return preMonday;

}

// 獲得上周星期日的日期

public String getPreviousWeekSunday() {

weeks = 0;

weeks--;

int mondayPlus = this.getMondayPlus();

GregorianCalendar currentDate = new GregorianCalendar();

currentDate.add(GregorianCalendar.DATE, mondayPlus + weeks); //本周周一的天數減去1天

Date monday = currentDate.getTime();

DateFormat df = DateFormat.getDateInstance();

String preMonday = df.format(monday);

return preMonday;

}

// 獲得上周星期一的日期

public String getPreviousWeekday() {

weeks--;

int mondayPlus = this.getMondayPlus();

GregorianCalendar currentDate = new GregorianCalendar();

currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);//本周周一的天數減去7天

Date monday = currentDate.getTime();

DateFormat df = DateFormat.getDateInstance();

String preMonday = df.format(monday);

return preMonday;

}

// 獲得下周星期一的日期

public String getNextMonday() {

weeks++;

int mondayPlus = this.getMondayPlus();

GregorianCalendar currentDate = new GregorianCalendar();

currentDate.add(GregorianCalendar.DATE, mondayPlus + 7);//本周周一的天數加7天

Date monday = currentDate.getTime();

DateFormat df = DateFormat.getDateInstance();

String preMonday = df.format(monday);

return preMonday;

}

// 獲得下周星期日的日期

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();

String preMonday = df.format(monday);

return preMonday;

}

//----------------------------------------------------------

// 獲取當月第一天

public String getFirstDayOfMonth() {

String str = "";

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

Calendar date = Calendar.getInstance();

date.set(Calendar.DATE, 1);// 設為當前月的1號

str = sdf.format(date.getTime());

return str;

}

// 計算當月最後一天,返回字符串

public String getDefaultDay() {

String str = "";

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

Calendar date = Calendar.getInstance();

date.set(Calendar.DATE, 1);// 設為當前月的1號

date.add(Calendar.MONTH, 1);// 加一個月,變為下月的1號

date.add(Calendar.DATE, -1);// 減去一天,變為當月最後一天

str = sdf.format(date.getTime());

return str;

}

// 上月第一天

public String getPreviousMonthFirst() {

String str = "";

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

Calendar date = Calendar.getInstance();

date.set(Calendar.DATE, 1);// 設為當前月的1號

date.add(Calendar.MONTH, -1);// 減一個月,變為上月的1號

str = sdf.format(date.getTime());

return str;

}

// 獲得上月最後一天的日期

public String getPreviousMonthEnd() {

String str = "";

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

Calendar date = Calendar.getInstance();

date.add(Calendar.MONTH, -1);// 減一個月

date.set(Calendar.DATE, 1);// 把日期設置為當月第一天

date.roll(Calendar.DATE, -1);// 日期回滾一天,也就是本月最後一天

// date.set(Calendar.DATE, 1);

// date.add(Calendar.DATE,-1);

str = sdf.format(date.getTime());

return str;

}

// 獲得下個月第一天的日期

public String getNextMonthFirst() {

String str = "";

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

Calendar date = Calendar.getInstance();

date.add(Calendar.MONTH, 1);// 減一個月

date.set(Calendar.DATE, 1);// 把日期設置為當月第一天

str = sdf.format(date.getTime());

return str;

}

// 獲得下個月最後一天的日期

public String getNextMonthEnd() {

String str = "";

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

Calendar date = Calendar.getInstance();

date.add(Calendar.MONTH, 1);// 加一個月

date.set(Calendar.DATE, 1);// 把日期設置為當月第一天

date.roll(Calendar.DATE, -1);// 日期回滾一天,也就是本月最後一天

str = sdf.format(date.getTime());

return str;

}

//---------------------------------------------------------

//獲得今天是這個月的第幾周

public static int getWeekOfMonth() {

return calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH);

}

//獲得當前年份

public static int getYear() {

return calendar.get(Calendar.YEAR);

}

//獲得當前年份

public static int getMonth() {

return calendar.get(Calendar.MONTH) + 1;

}

//獲得今天在本年的第幾天

public static int getDayOfYear() {

return calendar.get(Calendar.DAY_OF_YEAR);

}

//獲得今天在本月的第幾天(獲得當前日)

public static int getDayOfMonth() {

return calendar.get(Calendar.DAY_OF_MONTH);

}

//獲得今天在本周的第幾天

public static int getDayOfWeek() {

return calendar.get(Calendar.DAY_OF_WEEK);

}

//得到二個日期間的間隔天數

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 Date getTimeYearNext() {

calendar.add(Calendar.DAY_OF_YEAR, 183);

return calendar.getTime();

}

public static String convertDateToString(Date dateTime){

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

return df.format(dateTime);

}

//---------------------------------------------------------------

private int getYearPlus() {

Calendar cd = Calendar.getInstance();

int yearOfNumber = cd.get(Calendar.DAY_OF_YEAR);// 獲得當天是一年中的第幾天

cd.set(Calendar.DAY_OF_YEAR, 1);// 把日期設為當年第一天

cd.roll(Calendar.DAY_OF_YEAR, -1);// 把日期回滾一天。

int MaxYear = cd.get(Calendar.DAY_OF_YEAR);

if (yearOfNumber == 1) {

return -MaxYear;

} else {

return 1 - yearOfNumber;

}

}

// 獲得本年第一天的日期

public String getCurrentYearFirst() {

int yearPlus = this.getYearPlus();

GregorianCalendar currentDate = new GregorianCalendar();

currentDate.add(GregorianCalendar.DATE, yearPlus);

Date yearDay = currentDate.getTime();

DateFormat df = DateFormat.getDateInstance();

String preYearDay = df.format(yearDay);

return preYearDay;

}

// 獲得本年最後一天的日期 *

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();

String preYearDay = df.format(yearDay);

return preYearDay;

}

// 獲得明年最後一天的日期

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;

}

// 獲得本季度第一天

public String getThisSeasonFirstTime() {

int month = calendar.get(Calendar.MONTH) + 1;

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;

// years+"-"+String.valueOf(start_month)+"-1";//getLastDayOfMonth(years_value,start_month);

int end_days = getLastDayOfMonth(years_value, end_month);

String seasonDate = years_value + "-" + start_month + "-" + start_days;

return seasonDate;

}

// 獲得本季度最後一天

public String getThisSeasonFinallyTime() {

int month =calendar.get(Calendar.MONTH) + 1;

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;// years+"-"+String.valueOf(start_month)+"-1";//getLastDayOfMonth(years_value,start_month);

int end_days = getLastDayOfMonth(years_value, end_month);

String seasonDate = years_value + "-" + end_month + "-" + end_days;

return seasonDate;

}

//------------------------------------------------------------------------------

//根據一個日期,返回是星期幾的字符串

public static String getWeek(String sdate) {

// 再轉換為時間

Date date = CalendarUtil.strToDate(sdate);

Calendar c = Calendar.getInstance();

c.setTime(date);

// int hour=c.get(Calendar.DAY_OF_WEEK);

// hour中存的就是星期幾了,其範圍 1~7

// 1=星期日 7=星期六,其他類推

return new SimpleDateFormat("EEEE").format(c.getTime()); //EEEE代表星期幾

}

//將短時間格式字符串轉換為時間 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;

}

/* private int getMonthPlus() {

Calendar cd = Calendar.getInstance();

int monthOfNumber = cd.get(Calendar.DAY_OF_MONTH);

cd.set(Calendar.DATE, 1);// 把日期設置為當月第一天

cd.roll(Calendar.DATE, -1);// 日期回滾一天,也就是最後一天

MaxDate = cd.get(Calendar.DATE);

if (monthOfNumber == 1) {

return -MaxDate;

} else {

return 1 - monthOfNumber;

}

} */

// 獲得本年有多少天

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;

}

//獲取某年某月的最後一天

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;

}

/**

* 計算閏年和平年

* 閏年二月是29天,但不是能被4整除的就是閏年

* @param year

* @return

*/

private boolean isLeapYear(int year) {

boolean ison = true;

if((year%4==0&&year%100!=0)||year%400==0) {

ison = true;//閏年

}else {

ison = false;//平年

}

return ison;

}

//系統當前時間

public static String getCurrentDate (){

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

return sdf.format(calendar.getTime());

}

//得到幾天前的時間

public static String getDateBefore(String d,int day){

Calendar date =Calendar.getInstance();

Date dd = strToDate(d);

date.setTime(dd);

date.set(Calendar.DATE,date.get(Calendar.DATE)-day);

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

return sdf.format(date.getTime());

}

/* //得到幾天後的時間

public static Date getDateAfter(Date d,int day){

Calendar now =Calendar.getInstance();

now.setTime(d);

now.set(Calendar.DATE,now.get(Calendar.DATE)+day);

return now.getTime();

} */

//計算月份差

public static int getMonthSpace(String firstTime,String lastTime) {

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

Calendar c1 = Calendar.getInstance();

Calendar c2 = Calendar.getInstance();

try {

c1.setTime(sdf.parse(lastTime));

c2.setTime(sdf.parse(firstTime));

} catch (ParseException e) {

e.printStackTrace();

}

int result =(c1.get(Calendar.YEAR)-c2.get(Calendar.YEAR))*12+(c1.get(Calendar.MONTH)-c2.get(Calendar.MONTH));

return result ==0 ? 1 : result;

}

}

關於Calendar的一些用法總結