package com.njyunzhi.pet_identity.common;

import java.time.*;
import java.time.format.DateTimeFormatter;

public class DateUtils {
    public static LocalDateTime from(String str, DateTimeFormatter fmt) {
        return LocalDateTime.parse(str, fmt);
    }

    public static LocalDateTime from(String str, String formater) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(formater);
        return LocalDateTime.parse(str, fmt);
    }

    public static long daysBetween(LocalDateTime dt1, LocalDateTime dt2) {
        Duration duration = Duration.between(dt1, dt2);
        return duration.toDays();
    }

    public static String toString(LocalDateTime dt, String formater) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formater);
        return dt.format(formatter);
    }

    public static String weekDay(LocalDateTime dt) {
        String[] week = new String[]{"一", "二", "三", "四", "五", "六", "日"};
        DayOfWeek dayOfWeek = dt.getDayOfWeek();
        int inx = dayOfWeek.getValue() - 1;
        return String.format("星期%s", week[inx]);
    }

    /**
     * 毫秒转 UTC 时间
     * @param milliseconds
     * @return
     */
    public static LocalDateTime getDateTime(long milliseconds) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), ZoneOffset.UTC);
    }

    public static LocalDateTime getDayStart(String dt) {
        if (dt == null || dt.equals("")) return null;
        return from(dt + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
    }

    public static LocalDateTime getDayEnd(String dt) {
        if (dt == null || dt.equals("")) return null;
        return from(dt + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
    }

    public static String today(String ...formaters) {
        String formater = "yyyy-MM-dd";
        if (formaters.length > 0) {
            formater = formaters[0];
        }

        return toString(LocalDateTime.now(ZoneId.of("Asia/Shanghai")), formater);
    }
}
