package com.example.iot_controlhost.utils;

import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    /**
     * 计算从给定日期到今天的天数，包含当天
     *
     * @param date
     * @return
     */
    public static int daysFromTodayInclusive(Date date) {
        if (date == null) {
            throw new IllegalArgumentException("date cannot be null");
        }

        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        cal1.setTime(date);
        cal2.setTime(new Date());

        resetTime(cal1);
        resetTime(cal2);

        long diffMillis = cal2.getTimeInMillis() - cal1.getTimeInMillis();
        int days = (int) (diffMillis / (24 * 60 * 60 * 1000));

        if (days < 0) {
            // date在未来
            return days;
        }else{
            // 时间在过去或今天
            return days + 1;
        }
    }


    private static void resetTime(Calendar cal) {
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
    }
}