|
|
* 今 天是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(); } |
|