Java 推算日期(计算距今多少年,多少月,多少天的日期)

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

public final class Utils
{
    
    /**
     * get any time which you want before or after today.
     * @param year  by number years(before or after this year) default:0
     * @param month by number months(before or after this month)default:0,no change
     * @param day   by number day(before or after this day)default:0,no change
     * @return
     */
    public static Date getCountDate(int year, int month, int day){
        
        Calendar cal = Calendar.getInstance ();
        cal.add (Calendar.YEAR, year);
        cal.add (Calendar.MONDAY, month);
        cal.add (Calendar.DATE, day);
        
        return cal.getTime ();
    }
    

    public static String dateToString (Date date)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String temp = format.format (date);

        return temp;
    }
    
    public static void main(String[] args){

        Date today = Utils.getCountDate (0, 0, 0);
        Date oneYearBefore = Utils.getCountDate (-1, 0, 0);
        Date oneMonthBefore = Utils.getCountDate (0, -1, 0);
        Date oneDayBefore = Utils.getCountDate (0, 0, -1);
        Date oneYearAfter = Utils.getCountDate (1, 0, 0);
        Date oneMonthAfter = Utils.getCountDate (0, 1, 0);
        Date oneDayAfter = Utils.getCountDate (0, 0, 1);
        
        System.out.println (today + "\t" + Utils.dateToString (today));
        System.out.println (oneYearBefore + "\t" + Utils.dateToString (oneYearBefore));
        System.out.println (oneMonthBefore + "\t" + Utils.dateToString (oneMonthBefore));
        System.out.println (oneDayBefore + "\t" + Utils.dateToString (oneDayBefore));
        System.out.println (oneYearAfter + "\t" + Utils.dateToString (oneYearAfter));
        System.out.println (oneMonthAfter + "\t" + Utils.dateToString (oneMonthAfter));
        System.out.println (oneDayAfter + "\t" + Utils.dateToString (oneDayAfter));
    }
}

 

Result:

 

Mon Oct 24 16:09:45 CST 2011 2011-10-24
Sun Oct 24 16:09:45 CST 2010 2010-10-24
Sat Sep 24 16:09:45 CST 2011 2011-09-24
Sun Oct 23 16:09:45 CST 2011 2011-10-23
Wed Oct 24 16:09:45 CST 2012 2012-10-24
Thu Nov 24 16:09:45 CST 2011 2011-11-24
Tue Oct 25 16:09:45 CST 2011 2011-10-25

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值