java Calender類 日期的加減

* 今 天是2006年11月3日 是今年的第307天 c.getTime()的結果: Fri Nov 03 11:31:47 CST 2006 new Date()的結果: Fri Nov 03 11:31:47 CST 2006 17天后是Thu Feb 02 11:31:47 CST 2006


public class test1 {

public static void main(String[] args) {
Calendar c = Calendar.getInstance();
int year=c.get(Calendar.YEAR);


int month=c.get(Calendar.MONTH)+1;
int date=c.get(Calendar.DATE);
System.out.println("今天是"+year+"年"+month+"月"+date+"日");
System.out.println("是今年的第"+c.get(Calendar.DAY_OF_YEAR)+"天");
System.out.println("c.getTime()的結果: "+c.getTime());
System.out.println("new Date()的結果: "+new Date());
c.set(Calendar.DAY_OF_YEAR, date + 30);
System.out.println("17天后是"+c.getTime());
}

}


/**  
* 得到幾天前的時間
*
* @param d
* @param day
* @return
*/
public static Date getDateBefore(Date d, int day) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
return now.getTime();
}
/**
* 得到幾天後的時間
*
* @param d
* @param day
* @return
*/
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();
}


注意int month=c.get(Calendar.MONTH)+1哦,好像系統是從0開始計月份,到了12月就歸零了。所以單獨取月份時,要在後面加一才能得到當前的月份。


calender日期加減後賦值給Date類型
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String time=sdf.format(new Date());
Calendar cd = Calendar.getInstance();

try {
cd.setTime(sdf.parse(time));
} catch (ParseException e) {
e.printStackTrace();
}
cd.add(Calendar.DATE, 1);//增加一天
//cal.add(Calendar.DATE, -1); //減一天
//cd.add(Calendar.MONTH, 1);//增加一月
Date date=cd.getTime();
System.out.println(sdf.format(date));



將yyyy//MM/dd的字符串類型轉爲Date類型

							 SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
str12 = format.parse(str12_1);


在excel導入數據時,日期類型的數據直接獲取

CellType t1 = st.getCell(11, row).getType();
Date regDate = null;
Date str12=null;//出生年月,不能爲空
if (t1 == CellType.DATE)
{
DateCell regCell = (DateCell) st.getCell(11, row);
str12 = regCell.getDate();
}
發佈了33 篇原創文章 · 獲贊 0 · 訪問量 2722
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章