计算两个人相爱的天数

输入相爱日期即可打印出两个人相爱的天数

package cn.jason.service;

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

/**
 * @author Jason
 * @date 2020年2月17日09:27:38
 * @deprecated 计算两个人相爱天数
 */
public class TestLove {

	/**
     * 运行主方法
     * @param args
     * @throws ParseException
     */
    public static void main(String[] args) throws ParseException {

        System.out.print("请输入开始时间(例如:2019-12-21):");
        Scanner scanner = new Scanner(System.in);
        String in = scanner.next();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = simpleDateFormat.parse(in);
        Date nowDate = new Date(System.currentTimeMillis());
        System.out.println("相爱:" + differentDays(startDate,nowDate) + "天");

    }

    /**
     * 计算传入的两个时间相差的天数
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1,Date date2)
    {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2)   //不同一年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0)    //闰年
                {
                    timeDistance += 366;
                }
                else    //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2-day1) ;
        }
        else    //同一年
        {
            return day2-day1;
        }
    }

}

你可能感兴趣的:(Java)