package com.tanpu.community.util;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class TimeUtils {
    public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        return instant.toEpochMilli();
    }

    public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    //计算迄今时间
    public static String calUpToNowTime(LocalDateTime start) {
        Duration between = Duration.between(start, LocalDateTime.now());
        long duration = between.toMinutes();
        if (duration < 1) {
            return "刚刚";
        } else if (duration < 60) {
            return duration + "分钟前";
        } else if (duration < 60 * 24) {
            return duration / 60 + "小时前";
        } else if (start.getYear() == LocalDateTime.now().getYear()) {
            return start.format(DateTimeFormatter.ofPattern("MM-dd HH:mm:ss"));
        }
        return start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    //计算迄今时间
    public static long calMinuteTillNow(LocalDateTime start) {
        Duration between = Duration.between(start, LocalDateTime.now());
        return between.toMinutes();
    }


    //计算n天前的时间
    public static LocalDateTime getDaysBefore(Integer number){
        return LocalDateTime.now().minusDays(number);
    }

}