`
s_xy
  • 浏览: 19234 次
社区版块
存档分类
最新评论

时间日期处理之穿越1(日期加减天数)

阅读更多


package com.yao; 
 
import java.text.DateFormat; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date; 
 
 
public class DateTest { 
     
     
     public static void main(String[] args) throws ParseException   { 
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
      
     //假定今天的<strong>日期</strong>是"2014-2-21" 
     String strDate = "2014-2-21";  
     //穿越到30天前 
     Date beforeDays = getBeforeDate(strDate,30); 
     String beforeDaysString = formatter.format(beforeDays); 
     System.out.println("一年前的<strong>日期</strong>:"+beforeDaysString); 
      
    //穿越到10后 
     Date Afterdate =  getAfterDate(strDate,10); 
     String afterDateString = formatter.format(Afterdate); 
     System.out.println("一天以后的<strong>日期</strong>:"+afterDateString); 
       
     } 
      
     
      
     /**
      * 根据输入的<strong>日期</strong>字符串 和 提前天数 ,
      * 获得 指定<strong>日期</strong>提前几天的<strong>日期</strong>对象
      * @param dateString <strong>日期</strong>对象 ,格式如 2014-2-21
      * @param beforeDays 倒推的天数
      * @return 指定<strong>日期</strong>倒推指定天数后的<strong>日期</strong>对象
      * @throws ParseException 
     * @throws java.text.ParseException 
      */ 
     public static Date getBeforeDate(String dateString , int beforeDays) throws ParseException, java.text.ParseException{ 
       
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
      Date inputDate = dateFormat.parse(dateString); 
      Calendar cal = Calendar.getInstance(); 
      cal.setTime(inputDate); 
      int inputDayOfYear = cal.get(Calendar.DAY_OF_YEAR); 
      cal.set(Calendar.DAY_OF_YEAR , inputDayOfYear-beforeDays ); 
       
      return cal.getTime(); 
     } 
 
     /**
      * 根据输入的<strong>日期</strong>字符串 和 往后天数 ,
      * 获得 指定<strong>日期</strong>提前几天的<strong>日期</strong>对象
      * @param dateString <strong>日期</strong>对象 ,格式如 2014-2-21
      * @param afterDate 往后的天数
      * @return 指定<strong>日期</strong>往后指定天数后的<strong>日期</strong>对象
      * @throws ParseException
      */ 
     public static Date getAfterDate(String dateString,int afterDate) throws ParseException{ 
          DateFormat dateFororma = new SimpleDateFormat("yyyy-MM-dd"); 
          Date date = dateFororma.parse(dateString); 
          Calendar calendar = Calendar.getInstance(); 
          calendar.setTime(date); 
          calendar.add(calendar.DATE,afterDate); 
          date = calendar.getTime(); 
         return date; 
     } 
     
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics