java 日历类Calendar用法

如何获取昨天?取昨天的日期,本想的截出来日期减一就好了。又一想不对,如果今天是一号怎么办?

    现有两个办法

1:

Date as = new Date(new Date().getTime()-24*60*60*1000);
  SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
  String time = matter1.format(as);
  System.out.println(time);

  取出数字型的时间  再减去24*60*60*1000,就得到昨天的时间了;

这个有点过时了!

2: 

Calendar calendar = new GregorianCalendar();
 calendar.setTime(date);
 calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
 date=calendar.getTime(); //这个时间就是日期往后推一天的结果 

这个方法很方便,年月日都可以随心所欲的变!

如何获取指定日期的前一天或者后一天呢?

/** 
* 获得指定日期的前一天 
* @param specifiedDay 
* @return 
* @throws Exception 
*/ 
public static String getSpecifiedDayBefore(String specifiedDay){ 
//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
Calendar c = Calendar.getInstance(); 
Date date=null; 
try { 
date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay); 
} catch (ParseException e) { 
e.printStackTrace(); 
} 
c.setTime(date); 
int day=c.get(Calendar.DATE); 
c.set(Calendar.DATE,day-1); 

String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()); 
return dayBefore; 
} 
/** 
* 获得指定日期的后一天 
* @param specifiedDay 
* @return 
*/ 
public static String getSpecifiedDayAfter(String specifiedDay){ 
Calendar c = Calendar.getInstance(); 
Date date=null; 
try { 
date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay); 
} catch (ParseException e) { 
e.printStackTrace(); 
} 
c.setTime(date); 
int day=c.get(Calendar.DATE); 
c.set(Calendar.DATE,day+1); 

String dayAfter=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()); 
return dayAfter; 
} 

 

原文地址:https://www.cnblogs.com/azhqiang/p/6483718.html