问题描述
JSONObject
的getTimestamp
提供将原始数据转换为时间戳的方法;
但是实际使用时,发现如果日期小于等于1970-01-01
,提示无法转换为timestamp
类型;
解决办法
手工转换:timestamp
java代码
import com.alibaba.fastjson.JSONObject;
import java.sql.Timestamp;
...
public void testJsonObject() {
JSONObject jo = new JSONObject();
jo.put("d1", "2020-06-23");
jo.put("d2", "1970-01-02");
jo.put("d3", "1970-01-01");
System.out.println("d1:" + jo.getTimestamp("d1"));
System.out.println("d2:" + jo.getTimestamp("d2"));
try {
// 如果日期小于等于`1970-01-01`,提示无法转换为`timestamp`类型
System.out.println("d3:" + jo.getTimestamp("d3"));
} catch (Exception e) {
System.out.println("d3自动转换错误:" + e.getMessage());
}
System.out.println("d3手工转换:" + new Timestamp(jo.getDate("d3").getTime()));
}
...
输出结果
d1:2020-06-23 00:00:00.0
d2:1970-01-02 00:00:00.0
d3自动转换错误:can not cast to Timestamp, value : 1970-01-01
d3手工转换:1970-01-01 00:00:00.0