欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DateUtils工具类

程序员文章站 2022-04-25 20:08:09
...
package com.grm.util;

import com.grm.enums.ErrorEnum;
import com.grm.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

@Slf4j
public class DateUtils {
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String EXCEL_DATE_FORMAT = "EEE MMM dd HH:mm:ss zzz yyyy";

    /**
     * 获得所需要的日期格式
     *
     * @param dateString
     * @param format     默认yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static Date dateStringToDate(String dateString, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        if (StringUtils.isNotEmpty(format)) {
            formatter.applyPattern(format);
        }
        Date formatDate = null;
        try {
            formatDate = formatter.parse(dateString);
        } catch (ParseException e) {
            log.error("[DateUtils] dateStringToDate parse error : {}", e);
            throw new BusinessException(ErrorEnum.DATE_PARSE_ERROR);
        }
        return formatDate;
    }

    public static String dateStringToOtherDateString(String dateString, String fromFormat, String toFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(fromFormat, Locale.US);
        Date date = null;
        try {
            date = sdf.parse(dateString);
        } catch (ParseException e) {
            log.error("[DateUtils] dateStringToOtherDateString parse error : {}", e);
            throw new BusinessException(ErrorEnum.DATE_PARSE_ERROR);
        }
        sdf.applyPattern(toFormat);
        return sdf.format(date);
    }
}

相关标签: # 6 框架