Calendar类的静态方法getInstance()可以初始化一个日历对象:Calendar now = Calendar.getInstance();
1.Calendar的基本用法
calendar.add(Calendar.DATE, -1); //得到前一天
calendar.add(Calendar.MONTH, -1); //得到前一个月
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1;
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");
4.案例
a.网上找的小案例 判断当前日期是星期几
public static int dayForWeek(String pTime) throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(format.parse(pTime));
int dayForWeek = 0;
if(c.get(Calendar.DAY_OF_WEEK) == 1){
dayForWeek = 7;
}else{
dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
}
return dayForWeek;
}
b.项目中的案例 获取某一天的时间
public String getTime(String condition){
Date dNow = new Date();//当前时间
Date dBefore = new Date();
Calendar calendar = Calendar.getInstance();//得到日历
calendar.setTime(dNow);//date转Calendar
if(condition.equals("week")){
calendar.add(Calendar.DAY_OF_MONTH, -7);//设置为前七天
}else if(condition.equals("month")){
calendar.add(Calendar.MONTH, -1);//设置为一个月前
}
dBefore = calendar.getTime();//Calendar转date
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//设置时间格式
return sdf.format(dBefore);//返回日期
}