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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值