JAVA日期工具类

import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.util.Date;  

public class DateUtil {

    /**
     * @param args
     *void
     */
    public static void main(String[] args) {
        Date date = new Date();  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
        String specifiedDay = sdf.format(date);  
        //当前日期前一天
        System.out.println(getSpecifiedDayBefore(specifiedDay));  
        //当前日期后一天
        System.out.println(getSpecifiedDayAfter(specifiedDay));
        System.out.println(getDayAfterReturnDate(date));  //输出日期格式

    }
    
    /**
     * 获得指定日期的后一天,返回日期类型
     * @param date
     * @return
     *Date
     */
    public static Date  getDayAfterReturnDate(Date date){

        Calendar cal = Calendar.getInstance();  
        cal.setTime(date);  
        cal.set(Calendar.HOUR_OF_DAY, 0);    
        cal.set(Calendar.MINUTE, 0);   
        cal.set(Calendar.SECOND, 0); //设置时分秒都为0  
        date = cal.getTime();       //day为2008-08-08 00:00:00  
        cal.add(Calendar.DAY_OF_YEAR, 1);  //天加1  
        Date date2 = cal.getTime();   //d2为2008-08-09 00:00:00  
        
        return date2;
    }
    
    /**
     * 获得指定日期的前一天
     * @param specifiedDay
     * @return
     * @throws Exception
     */  
    public static String getSpecifiedDayBefore(String specifiedDay) {//可以用new Date().toLocalString()传递参数  
        Calendar c = Calendar.getInstance();  
        Date date = null;  
        try {  
            date = new SimpleDateFormat("yyyy-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
     * @throws java.text.ParseException
     */  
    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;  
    }  

}

你可能感兴趣的:(java)