Analog of ORACLE function MONTHS_BETWEEN in Java

后端 未结 8 474
时光说笑
时光说笑 2021-01-12 09:56

Does Java have some analog of Oracle\'s function MONTHS_BETWEEN?

8条回答
  •  悲&欢浪女
    2021-01-12 10:21

    You can do that with :

    public static int monthsBetween(Date minuend, Date subtrahend){  
    
        Calendar cal = Calendar.getInstance();   
        cal.setTime(minuend);  
        int minuendMonth =  cal.get(Calendar.MONTH);  
        int minuendYear = cal.get(Calendar.YEAR);  
        cal.setTime(subtrahend);  
        int subtrahendMonth =  cal.get(Calendar.MONTH);  
        int subtrahendYear = cal.get(Calendar.YEAR);  
    
        return ((minuendYear - subtrahendYear) * (cal.getMaximum(Calendar.MONTH)+1)) +    
        (minuendMonth - subtrahendMonth);  
    }  
    

    Edit :

    According to this documentation MONTHS_BETWEEN return a fractional result, I think this method do the same :

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date d = sdf.parse("02/02/1995");
        Date d2 = sdf.parse("01/01/1995");
        System.out.println(monthsBetween(d, d2));
    
    }
    
    public static double monthsBetween(Date baseDate, Date dateToSubstract){  
    
        Calendar cal = Calendar.getInstance();   
        cal.setTime(baseDate);
        int baseDayOfYear = cal.get(Calendar.DAY_OF_YEAR);  
        int baseMonth =  cal.get(Calendar.MONTH);  
        int baseYear = cal.get(Calendar.YEAR);  
    
        cal.setTime(dateToSubstract);  
        int subDayOfYear = cal.get(Calendar.DAY_OF_YEAR);
        int subMonth =  cal.get(Calendar.MONTH);  
        int subYear = cal.get(Calendar.YEAR);  
    
        //int fullMonth = ((baseYear - subYear) * (cal.getMaximum(Calendar.MONTH)+1)) +    
        //(baseMonth - subMonth);  
        //System.out.println(fullMonth);
    
        return ((baseYear - subYear) * (cal.getMaximum(Calendar.MONTH)+1)) +   
               (baseDayOfYear-subDayOfYear)/31.0;
    } 
    

提交回复
热议问题