/*
     * 比较两个时间点相差多少年。
     */
    public static long compareTime(String time){
        String myString=null;
        if(time==null){
            myString="0000-00-00";
        }else{
            myString = time;
        }
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         Calendar start = Calendar.getInstance();
         Calendar end = Calendar.getInstance(); 
        
        Date now1 = new Date();
        String now=sdf.format(now1);
        Date date = null;
        try {
        now1 = sdf.parse(now);
        date = sdf.parse(myString);
        start.setTime(date);
        end.setTime(now1);
        } catch (Exception e) {
        e.printStackTrace();
        }
        if(end.get(Calendar.YEAR)>start.get(Calendar.YEAR)){
            int year=end.get(Calendar.YEAR)-start.get(Calendar.YEAR);
            if(end.get(Calendar.MONTH)+1>=start.get(Calendar.MONTH)+1){
                if(end.get(Calendar.DATE)>=start.get(Calendar.DATE)){
                    return year;
                }else{
                    return year-1;
                }
            }else{
                return year-1;
            }
            
        }else{
            return 0;
        }
        
    }

 有时候会要求将一个日期的月份加一返回。

  public static Map<String,Integer> MOUTHMAP=new HashMap<String, Integer>();

 static{
        MOUTHMAP.put("01", 1);
        MOUTHMAP.put("02", 2);
        MOUTHMAP.put("03", 3);
        MOUTHMAP.put("04", 4);
        MOUTHMAP.put("05", 5);
        MOUTHMAP.put("06", 6);
        MOUTHMAP.put("07", 7);
        MOUTHMAP.put("08", 8);
        MOUTHMAP.put("09", 9);
        MOUTHMAP.put("10", 10);
        MOUTHMAP.put("11", 11);
        MOUTHMAP.put("12", 12);
}

/*
     * 对月份加一返回月份操作。
     * 
     */
    public static String nextMouth(String mouth){
        if(mouth==null||"".equals(mouth)){
            return null; 
        }
        String[] YMD=mouth.split("-"); 
        String year=YMD[0];
        String nextmouth=YMD[1];
        String day=YMD[2];
        if(MOUTHMAP.get(YMD[1])==12){
            nextmouth="01";
            year=String.valueOf(Integer.parseInt(year)+1);
        }else{
            int m=MOUTHMAP.get(nextmouth);
            int n=m+1;
              for (Map.Entry<String, Integer> entry : MOUTHMAP.entrySet()) {
                     if(entry.getValue()==n){
                         nextmouth=entry.getKey();
                     }
                }
        }
        return year+"-"+nextmouth+"-"+day;
    }
    

 

posted on 2018-07-06 17:05  王衙内  阅读(5604)  评论(2编辑  收藏  举报