package cn.axzo.msg.center.utils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/**
 * @description
 *   日期格式转换工具类
 *
 * @author cold_blade
 * @date 2023/9/28
 * @version 1.0
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class DateFormatUtil {

    public static String toReadableString(Date date) {
        if (date == null)
            return null;
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    public static LocalDateTime toLocalDateTime(Date date) {
        if (Objects.isNull(date)) {
            return null;
        }
        ZoneId zoneId = ZoneId.systemDefault();
        return date.toInstant().atZone(zoneId).toLocalDateTime();
    }

    public static Long toTimestamp(LocalDateTime dateTime) {
        return Optional.ofNullable(dateTime)
                .map(v -> v.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli())
                .orElse(null);
    }

    public static Date toDate(LocalDateTime dateTime) {
        return Optional.ofNullable(dateTime)
                .map(v -> toTimestamp(dateTime))
                .map(Date::new)
                .orElse(null);
    }
}
