package com.ruoyi.hywz.utils;

import com.ruoyi.common.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

/**
 * @author: jxh
 * @description:
 * @create: 2024/7/30
 */
public class DateUtil {

    public static final SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final SimpleDateFormat f2 = new SimpleDateFormat("yyyy-MM-dd");
    public static final DateTimeFormatter f2_2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final SimpleDateFormat f3 = new SimpleDateFormat("yyyy.MM");
    public static final SimpleDateFormat f4 = new SimpleDateFormat("yyyy-MM");
    public static final DateTimeFormatter f4_2 = DateTimeFormatter.ofPattern("yyyy-MM");

    public static String getFormat(Date date, SimpleDateFormat format) {
        try {
            return format.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    public static String getDate(String dateTime) {
        try {
            String date = dateTime.substring(0, 10);
            LocalDate parse = LocalDate.parse(date, DateUtil.f2_2);
            return parse.format(DateUtil.f2_2);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取给定年月的月初和月末日期
     *
     * @param yearMonth 形式为"yyyy-MM"的字符串
     * @return 包含月初和月末日期的数组
     */
    public static String[] getMonthStartAndEnd(String yearMonth) {
        if (StringUtils.isEmpty(yearMonth)) {
            return null;
        }
        // 解析年月
        LocalDate date = LocalDate.parse(yearMonth + "-01", f2_2);

        // 获取月初日期
        LocalDate startOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());

        // 获取月末日期
        LocalDate endOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());

        // 格式化为字符串
        String startOfMonthStr = startOfMonth.format(f2_2);
        String endOfMonthStr = endOfMonth.format(f2_2);

        // 返回结果
        return new String[] { startOfMonthStr, endOfMonthStr };
    }
}
