日期类的加减及java中所以日期类的操作算法大全
2009-09-22 00:00:00 来源:WEB开发网(2)计算一年中的第几星期是几号
1SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
2Calendar cal=Calendar.getInstance();
3cal.set(Calendar.YEAR, 2006);
4cal.set(Calendar.WEEK_OF_YEAR, 1);
5cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
6System.out.println(df.format(cal.getTime()));
输出:
2006-01-02
5.add()和roll()的用法(不太常用)
(1)add()方法
1SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
2Calendar cal=Calendar.getInstance();
3cal.set(Calendar.YEAR, 2006);
4cal.set(Calendar.MONTH, 8);
5cal.set(Calendar.DAY_OF_MONTH, 3);
6cal.add(Calendar.DATE, -4);
7Date date=cal.getTime();
8System.out.println(df.format(date));
9cal.add(Calendar.DATE, 4);
10date=cal.getTime();
11System.out.println(df.format(date));
输出:
2006-08-30
2006-09-03
(2)roll方法
1cal.set(Calendar.YEAR, 2006);
2cal.set(Calendar.MONTH, 8);
3cal.set(Calendar.DAY_OF_MONTH, 3);
4cal.roll(Calendar.DATE, -4);
5date=cal.getTime();
6System.out.println(df.format(date));
7cal.roll(Calendar.DATE, 4);
8date=cal.getTime();
9System.out.println(df.format(date));
输出:
2006-09-29
2006-09-03
可见,roll()方法在本月内循环,一般使用add()方法;
更多精彩
赞助商链接