自定义DateFormat
开发中最常用的日期解析类是simpleDateFormat,往往能完成大部分对日期解析、或者转成固定格式字符串的需求。但有时候对pattern的解析有更加复杂的需求,比如忽略掉pattern中的某些单词,或者按照自定义的脚本进行解析,这时候就需要自己定义规则了。
举个例子来说,希望将2020/8/29 转换成 “FY2020”来展示,如果pattern是“FYyyyy”,明显解析出来的结果并不是我们想要的。
以该需求为例,下面自定义一个日期处理类AdvanceDateFormat
package date;
import java.text.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.*;
public class AdvanceDateFormat extends DateFormat {
public AdvanceDateFormat(String pattern, String ignoreWord) {
this.fmt = createDateFormat(pattern, ignoreWord);
}
/**
* 格式化时间
* */
@Override
public StringBuffer format(Date date, StringBuffer stringBuffer, FieldPosition fieldPosition) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
LocalDateTime ldate = LocalDateTime.of(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1,
cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND));
return stringBuffer.append(this.fmt.format(ldate));
}
@Override
public Date parse(String s, ParsePosition parsePosition) {
// do nothing
return null;
}
/**
* 构造DateTimeFormatter
* */
private DateTimeFormatter createDateFormat(String pattern, String ignoreWord) {
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder();
while(pattern.length() > 0) {
if(pattern.startsWith(ignoreWord)) {
dateTimeFormatterBuilder.appendLiteral(ignoreWord);//处理需要忽略的单词
pattern = pattern.replace(ignoreWord, "");
}
else if(pattern.indexOf(ignoreWord) > 0) {
String patternStr = pattern.substring(0, pattern.indexOf(ignoreWord));
dateTimeFormatterBuilder.appendPattern(patternStr);//添加pattern
pattern = pattern.replace(ignoreWord, "");
}
else {
dateTimeFormatterBuilder.appendPattern(pattern);//添加pattern
pattern = pattern.replace(pattern, "");
}
}
return dateTimeFormatterBuilder.toFormatter();
}
private DateTimeFormatter fmt;
}
测试类
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import date.AdvanceDateFormat;
/**
* @program: test2
*
* @description
*
* @author: Samur
*
* @create: 2020-05-22 17:01
**/
public class Test {
public static void main(String[] args) {
String pattern = "FYyyyy";
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);//使用simpleDateFormat 格式化时间
String dateStr = simpleDateFormat.format(date);
System.out.println(dateStr);
System.out.println("=========================================");
AdvanceDateFormat advanceDateFormat = new AdvanceDateFormat(pattern, "FY");
String dateFormat = advanceDateFormat.format(date).toString();
System.out.println(dateFormat);
}
}
测试结果
520202020
=========================================
FY2020
Process finished with exit code 0