mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-07-21 15:09:48 +08:00
support custom date format parse
This commit is contained in:
@@ -1,7 +1,13 @@
|
||||
package cn.hutool.json;
|
||||
|
||||
import cn.hutool.core.bean.OptionalBean;
|
||||
import cn.hutool.core.convert.Convert;
|
||||
import cn.hutool.core.convert.ConvertException;
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.getter.OptNullBasicTypeFromObjectGetter;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 用于JSON的Getter类,提供各种类型的Getter方法
|
||||
@@ -105,6 +111,26 @@ public interface JSONGetter<K> extends OptNullBasicTypeFromObjectGetter<K> {
|
||||
return (null == obj) ? null : obj.toBean(beanType);
|
||||
}
|
||||
|
||||
@Override
|
||||
default Date getDate(K key, Date defaultValue){
|
||||
String format = OptionalBean.ofNullable(getConfig()).getBean(JSONConfig::getDateFormat).get();
|
||||
if(StrUtil.isNotBlank(format)){
|
||||
// 用户指定了日期格式,获取日期属性时使用对应格式
|
||||
final String str = getStr(key);
|
||||
if(null == str){
|
||||
return defaultValue;
|
||||
}
|
||||
return DateUtil.parse(str, format);
|
||||
}
|
||||
|
||||
// 默认转换
|
||||
final Object obj = getObj(key);
|
||||
if (null == obj) {
|
||||
return defaultValue;
|
||||
}
|
||||
return Convert.toDate(obj, defaultValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定类型的对象<br>
|
||||
* 转换失败或抛出异常
|
||||
|
@@ -429,6 +429,27 @@ public class JSONObjectTest {
|
||||
Assert.assertEquals("{\"date\":[\"2020-06-05 11:16:11\"],\"bbb\":[\"222\"],\"aaa\":[\"123\"]}", json.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setDateFormatTest2(){
|
||||
JSONConfig jsonConfig = JSONConfig.create();
|
||||
jsonConfig.setDateFormat("yyyy#MM#dd");
|
||||
jsonConfig.setOrder(true);
|
||||
|
||||
Date date = DateUtil.parse("2020-06-05 11:16:11");
|
||||
JSONObject json = new JSONObject(jsonConfig);
|
||||
json.set("date", date);
|
||||
json.set("bbb", "222");
|
||||
json.set("aaa", "123");
|
||||
|
||||
String jsonStr = "{\"date\":\"2020#06#05\",\"bbb\":\"222\",\"aaa\":\"123\"}";
|
||||
|
||||
Assert.assertEquals(jsonStr, json.toString());
|
||||
|
||||
// 解析测试
|
||||
final JSONObject parse = JSONUtil.parseObj(jsonStr, jsonConfig);
|
||||
Assert.assertEquals(DateUtil.beginOfDay(date), parse.getDate("date"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getTimestampTest(){
|
||||
String timeStr = "1970-01-01 00:00:00";
|
||||
|
Reference in New Issue
Block a user