package com.izouma.jiashanxia.utils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

public class DateTimeUtils {
    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
    public static final String T_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
    public static final String DATE_FORMAT      = "yyyy-MM-dd";

    public static LocalDate toLocalDate(long ts) {
        if (String.valueOf(ts).length() > 10) {
            return LocalDate.from(Instant.ofEpochMilli(ts));
        } else {
            return LocalDate.from(Instant.ofEpochSecond(ts));
        }
    }

    public static LocalDateTime toLocalDateTime(long ts) {
        if (String.valueOf(ts).length() > 10) {
            return LocalDateTime.from(Instant.ofEpochMilli(ts));
        } else {
            return LocalDateTime.from(Instant.ofEpochSecond(ts));
        }
    }

    public static LocalDate toLocalDate(String str, String fmt) {
        return LocalDate.from(DateTimeFormatter.ofPattern(fmt).parse(str));
    }

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

    public static String format(TemporalAccessor temporal, String fmt) {
        return DateTimeFormatter.ofPattern(fmt).format(temporal);
    }

    public static long toTimestamp(TemporalAccessor temporal) {
        return Instant.from(temporal).toEpochMilli();
    }
}
