1.计算某一月份的***天数:
- Calendar time=Calendar.getInstance();
- time.clear();
- time.set(Calendar.YEAR,year); //year 为 int
- time.set(Calendar.MONTH,i-1);//注意,Calendar对象默认一月为0
- int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数
注:在使用set方法之前,必须先clear一下,否则很多信息会继承自系统当前时间
2.Calendar和Date的转化:
(1) Calendar转化为Date:
- Calendar cal=Calendar.getInstance();
- Date date=cal.getTime();
(2) Date转化为Calendar:
- Date date=new Date();
- Calendar cal=Calendar.getInstance();
- cal.setTime(date);
3.格式化输出日期时间 (这个用的比较多):
- Date date=new Date();
- SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
- String time=df.format(date);
- System.out.println(time);
4.计算一年中的第几星期:
(1)计算某一天是一年中的第几星期:
- Calendar cal=Calendar.getInstance();
- cal.set(Calendar.YEAR, 2006);
- cal.set(Calendar.MONTH, 8);
- cal.set(Calendar.DAY_OF_MONTH, 3);
- int weekno=cal.get(Calendar.WEEK_OF_YEAR);
(2)计算一年中的第几星期是几号:
- SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
- Calendar cal=Calendar.getInstance();
- cal.set(Calendar.YEAR, 2006);
- cal.set(Calendar.WEEK_OF_YEAR, 1);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- System.out.println(df.format(cal.getTime()));
- 输出:
- 2006-01-02
5.add()和roll()的用法(不太常用):
- (1)add()方法
- SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
- Calendar cal=Calendar.getInstance();
- cal.set(Calendar.YEAR, 2006);
- cal.set(Calendar.MONTH, 8);
- cal.set(Calendar.DAY_OF_MONTH, 3);
- cal.add(Calendar.DATE, -4);
- Date date=cal.getTime();
- System.out.println(df.format(date));
- cal.add(Calendar.DATE, 4);
- date=cal.getTime();
- System.out.println(df.format(date));
- 输出:
- 2006-08-30
- 2006-09-03
- (2)roll方法
- cal.set(Calendar.YEAR, 2006);
- cal.set(Calendar.MONTH, 8);
- cal.set(Calendar.DAY_OF_MONTH, 3);
- cal.roll(Calendar.DATE, -4);
- date=cal.getTime();
- System.out.println(df.format(date));
- cal.roll(Calendar.DATE, 4);
- date=cal.getTime();
- System.out.println(df.format(date));
- 输出:
- 2006-09-29
- 2006-09-03
可见,roll()方法在本月内循环,一般使用add()方法。
以上为常用java date 方法集合的***部分,如要完整了解,请关注第二部分。
【编辑推荐】