Java 计算年份,月份,剩余天数

实现很简单,两者时间进行比较。。。具体看下面代码!

package com.text;

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

public class Text1 {
    /**
     * TODO(description of this method)
     * 
     * @param args
     * @author c99999999 kevin 2016年4月25日 下午6:57:24
     * @since v1.0
     */
    public static void main(String[] args) {
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        Date d = null;
        try {
            d = df1.parse("2015-1-26");
        } catch(ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Calendar foretime = Calendar.getInstance();
        foretime.setTime(d);
        Calendar nowCalendar = Calendar.getInstance();
        int day = nowCalendar.get(Calendar.DAY_OF_MONTH) - foretime.get(Calendar.DAY_OF_MONTH);
        int month = nowCalendar.get(Calendar.MONTH) - foretime.get(Calendar.MONTH);
        int year = nowCalendar.get(Calendar.YEAR) - foretime.get(Calendar.YEAR);
        // 按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减。
        if(day < 0) {
            month -= 1;
            nowCalendar.add(Calendar.MONTH, -1);// 得到上一个月,用来得到上个月的天数。

            day = day + nowCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        if(month < 0) {
            month = (month + 12) % 12;
            year--;
        }
        System.out.println("结果:" + year + "年" + month + "月" + day + "天");
        for(int i = 0; i < month; i++) {
            nowCalendar.add(Calendar.MONTH, -1);// 得到上一个月,用来得到上个月的天数。

            day = day + nowCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        System.out.println("过去时间与现在有:" + year + "年" + "" + day + "天");

    }
}

结果:1年3月0天
过去时间与现在有:1年91天

原文地址:https://www.cnblogs.com/kevin-chen/p/5433939.html