MES-Springboot/docs/DateConverterConfig.java

72 lines
2.1 KiB
Java
Raw Normal View History

2019-06-15 09:52:43 +00:00
package com.songpeng.common.config;
2019-06-22 06:08:13 +00:00
import com.songpeng.common.utils.StringUtil;
2019-06-15 09:52:43 +00:00
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
*
*
* @author songpeng
* @date 2019/6/15
*/
@Component
public class DateConverterConfig implements Converter<String, Date> {
private static final List<String> FORMATS = new ArrayList<>(4);
static {
FORMATS.add("yyyy-MM");
FORMATS.add("yyyy-MM-dd");
FORMATS.add("yyyy-MM-dd hh:mm");
FORMATS.add("yyyy-MM-dd hh:mm:ss");
2019-06-17 09:56:13 +00:00
FORMATS.add("yyyy/MM");
FORMATS.add("yyyy/MM/dd");
FORMATS.add("yyyy/MM/dd hh:mm");
FORMATS.add("yyyy/MM/dd hh:mm:ss");
2019-06-15 09:52:43 +00:00
}
@Override
public Date convert(String source) {
String value = source.trim();
2019-06-22 06:08:13 +00:00
if (StringUtil.isBlank(value)) {
2019-06-15 09:52:43 +00:00
return null;
}
if (source.matches("^\\d{4}-\\d{1,2}$")) {
return parseDate(source, FORMATS.get(0));
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
return parseDate(source, FORMATS.get(1));
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
return parseDate(source, FORMATS.get(2));
} else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
return parseDate(source, FORMATS.get(3));
} else {
throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
}
}
/**
*
*
* @param dateStr String
* @param format String
* @return Date
*/
public Date parseDate(String dateStr, String format) {
Date date = null;
try {
DateFormat dateFormat = new SimpleDateFormat(format);
date = dateFormat.parse(dateStr);
} catch (Exception e) {
}
return date;
}
}