日期类的加减及java中所以日期类的操作算法大全
时间:2010-12-29 BlogJava jerry yang
1.计算某一月份的最大天数
1Calendar time=Calendar.getInstance();
2time.clear();
3time.set(Calendar.YEAR,year); //year为int
4time.set(Calendar.MONTH,i-1);//注意,Calendar对象默认一月为0
5int 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.格式化输出日期时间 (这个用的比较多)
其一
1Date date=new Date();
2SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
3String time=df.format(date);
4System.out.println(time);//2008-10-27 08:52:32
其二
1Calendar c = Calendar.getInstance();
2System.out.println(c.getTime());//Mon Oct 27 08:51:21 CST 2008
3SimpleDateFormat simpleDateTimeFormat = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss ");
4c = Calendar.getInstance(Locale.CHINESE);
5System.out.println(simpleDateTimeFormat.format(c.getTime()));// 2008-10-27 08:51:21
4.计算一年中的第几星期
(1)计算某一天是一年中的第几星期
1Calendar cal=Calendar.getInstance();
2cal.set(Calendar.YEAR, 2006);
3cal.set(Calendar.MONTH, 8);
4cal.set(Calendar.DAY_OF_MONTH, 3);
5int weekno=cal.get(Calendar.WEEK_OF_YEAR);
(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
日期类的加减及java中所以日期类的操作算法大全(2)
时间:2010-12-29 BlogJava jerry yang
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()方法;
6.计算两个任意时间中间的间隔天数(这个比较常用)
(1)传进Calendar对象
1 public int getIntervalDays(Calendar startday,Calendar endday){
2 if(startday.after(endday)){
3 Calendar cal=startday;
4 startday=endday;
5
|