码迷,mamicode.com
首页 > 编程语言 > 详细

Java 日期比较以及得到前后一天

时间:2015-07-08 18:22:11      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

    /**
     * 比较两个指定时间,结果为0 表示相同,< 0 则表示第一个时间早于第二个时间
     * @param firstDay
     * @param secondDay
     * @return
     */
    public static int compareto(String firstDay,String secondDay)  
    {  
        Calendar c = Calendar.getInstance();  
        Calendar c2 = Calendar.getInstance();  
        Date date = null;  
        Date date2 = null;  
        try  
        {  
            date = new SimpleDateFormat(DATE_FORMAT_PATTERN).parse(firstDay);  
            date2 = new SimpleDateFormat(DATE_FORMAT_PATTERN).parse(secondDay);  
        }  
        catch (ParseException e)  
        {  
            e.printStackTrace();  
        }  
        c.setTime(date);  
        c2.setTime(date2); 
        return c.compareTo(c2);
    } 
    /** 
     * 获得指定日期的前n天 
     *  
     * @param specifiedDay yy-MM-dd 
     * @return 
     * @throws Exception 
     */  
    public static String getBeforeDay(String specifiedDay,int n)  
    {  
        Calendar c = Calendar.getInstance();  
        Date date = null;  
        try  
        {  
            date = new SimpleDateFormat(DATE_FORMAT_PATTERN).parse(specifiedDay);  
        }  
        catch (ParseException e)  
        {  
            e.printStackTrace();  
        }  
        c.setTime(date);  
        int day = c.get(Calendar.DATE);  
        c.set(Calendar.DATE, day - n);  
      
        String dayBefore = new SimpleDateFormat(DATE_FORMAT_PATTERN).format(c.getTime());  
        return dayBefore;  
    } 
    
 /** 
     * 获得指定日期的后一天 
     *  
     * @param specifiedDay yy-MM-dd 
     * @return 
     */  
    public static String getAfterDay(String specifiedDay,int n)  
    {  
        Calendar c = Calendar.getInstance();  
        Date date = null;  
        try  
        {  
            date = new SimpleDateFormat(DATE_FORMAT_PATTERN).parse(specifiedDay);  
        }  
        catch (ParseException e)  
        {  
            e.printStackTrace();  
        }  
        c.setTime(date);  
        int day = c.get(Calendar.DATE);  
        c.set(Calendar.DATE, day + n);  
      
        String dayAfter = new SimpleDateFormat(DATE_FORMAT_PATTERN).format(c.getTime());  
        return dayAfter;  
    }

 

Java 日期比较以及得到前后一天

标签:

原文地址:http://www.cnblogs.com/panie2015/p/4630807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!