package com.sunwin.robot2ips.util;

import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description: Time工具类
 * @Author: shiwn
 * @Date: 2020/1/16 11:07
 */
public class TimeUtil {
    /**
     * @Description: 获取格式化后的Time
     * @Param: [hour：小时, minute：分钟]
     * @Author: shiwn
     * @Date: 2020/1/16 11:09
     */
    public static Time getFormatTime(String hour, String minute) {
        try {
            String time = hour + ":" + minute + ":00";
            Date date;
            DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            date = sdf.parse(time);
            return new Time(date.getTime());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @Description: 获取时间差（分钟）
     * @Param: [startTime：开始时间, endTime：结束时间]
     * @Author: shiwn
     * @Date: 2020/3/2 13:52
     */
    public static int getDiffTime(Date startTime, Date endTime) {
        long start = startTime.getTime();
        long end = endTime.getTime();
        //  判断是否有余数，自动补1分钟
        return (end - start) % (1000 * 60) == 0 ? (int) ((end - start) / (1000 * 60)) : (int) ((end - start) / (1000 * 60) + 1);
    }

    /**
     * @Description: 根据时间戳获取前 n 天的开始时间戳，例起始时间为：2020-12-01 00:00:00
     * @Param: [timestamp, day]
     * @Author: shiwn
     * @Date: 2020/12/7 10:01
     */
    public static Long getStartTimestamp(Long timestamp, Integer day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timestamp);
        day = 0 - day;
        calendar.add(Calendar.DATE, day);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    /**
     * @Description: 根据时间戳获取前 n 天的结束时间戳，例起始时间为：2020-12-01 00:00:00
     * @Param: [timestamp, day]
     * @Author: shiwn
     * @Date: 2020/12/7 10:15
     */
    public static Long getEndTimestamp(Long timestamp, Integer day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timestamp);
        day = 0 - day;
        calendar.add(Calendar.DATE, day);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTimeInMillis();
    }
}
