首页 > 代码库 > Java里的时间类以及函数
Java里的时间类以及函数
1.Java计算某一月份的最大天数
Calendar time=Calendar.getInstance();
time.clear();
time.set(Calendar.YEAR,year);
time.set(Calendar.MONTH,i-1);//注意,Calendar对象默认一月为0
int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数
注:在使用set方法之前,必须先clear一下,否则很多信息会继承自系统当前时间
2.Java中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.Java格式化输出日期时间
Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
System.out.println(df.format(date));
4.Java计算一年中的第几星期
(1)计算某一天是一年中的第几星期
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR, 2006);
cal.set(Calendar.MONTH,;
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,;
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,;
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()方法;