java的日期计算问题

 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()方法;

6.计算两个任意时间中间的间隔天数(这个比较常用)
(1)传进Calendar对象
    public int getIntervalDays(Calendar startday,Calendar endday)...{      
        if(startday.after(endday))...{
            Calendar cal=startday;
            startday=endday;
            endday=cal;
        }   
        long sl=startday.getTimeInMillis();
        long el=endday.getTimeInMillis();
      
        long ei=el-sl;          
        return (int)(ei/(1000*60*60*24));
    }
(2)传进Date对象

    public int getIntervalDays(Date startday,Date endday)...{       
        if(startday.after(endday))...{
            Date cal=startday;
            startday=endday;
            endday=cal;
        }       
        long sl=startday.getTime();
        long el=endday.getTime();      
        long ei=el-sl;          
        return (int)(ei/(1000*60*60*24));
    }
(3)改进精确计算相隔天数的方法
    public int getDaysBetween (Calendar d1, Calendar d2) ...{
        if (d1.after(d2)) ...{
      

你可能感兴趣的:(Android入门开发)