package com.awspaas.user.apps.donenow_sys;

import java.text.SimpleDateFormat;
import java.util.*;

public class DateUtil {

    public static final String DATE_FORMAT = "yyyy-MM-dd";
    public static final String DATE_FORMAT1 = "yyyyMMdd";
    public static final String DATE_FORMAT2 = "yyyyMMddHH";
    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_TIME_FORMAT1 = "yyyyMMddHHmmss";
    public static final String DATE_TIME_FORMAT2 = "yyyyMMddHHmmssSSS";
    public static final String DATE_TIME_FORMAT3 = "yyyy-MM-dd HH:mm";
    public static final String DATE_TIME_FORMAT4 = "yyMMddHHmmssSSS";
    public static final String DATE_TIME_FORMAT5 = "yyyy-MM-dd HH:mm:ss.SSS";

    private static final ThreadLocal<Map<String, SimpleDateFormat>> sThreadLocal = new ThreadLocal<>();

    public static String formatDate(Date date, String format) {
        if (format == null) {
            format = DATE_TIME_FORMAT;
        }
        return getFormat(format).format(date);
    }

    public static Date addDate(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        return calendar.getTime();
    }

    public static int getNowYear(){
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);//当前年份
        return year;
    }

    private static SimpleDateFormat getFormat(String pattern) {
        Map<String, SimpleDateFormat> strDateFormatMap = sThreadLocal.get();

        if (strDateFormatMap == null) {
            strDateFormatMap = new HashMap<>(10);
        }

        SimpleDateFormat simpleDateFormat = strDateFormatMap.get(pattern);
        if (simpleDateFormat == null) {
            simpleDateFormat = new SimpleDateFormat(pattern, Locale.getDefault());
            strDateFormatMap.put(pattern, simpleDateFormat);
            sThreadLocal.set(strDateFormatMap);
        }

        return simpleDateFormat;
    }

    public static String getCurrentDate() {
        return getCurrentDate(new Date(), DATE_FORMAT);
    }


    public static String getCurrentDate(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }


}
