【问题标题】:ISO8601 with milliseconds in json using JacksonISO8601 使用 Jackson 在 json 中以毫秒为单位
【发布时间】:2017-12-29 19:35:24
【问题描述】:
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;

objectMapper.setDateFormat(new ISO8601DateFormat());

很好,但这忽略了毫秒,我怎样才能在不使用非线程安全SimpleDateFormatter 的情况下在日期中获取它们?

https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/util/ISO8601DateFormat.java

【问题讨论】:

    标签: java json jackson datetime-format iso8601


    【解决方案1】:

    ISO8601DateFormat.format 调用ISO8601Utils.format(date),后者又调用format(date, false, TIMEZONE_Z) - false 参数告诉杰克逊不要包括毫秒。

    貌似没有办法配置这个类,也没有设置任何参数,还好可以扩展:

    public class ISO8601WithMillisFormat extends ISO8601DateFormat {
        @Override
        public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
            String value = ISO8601Utils.format(date, true); // "true" to include milliseconds
            toAppendTo.append(value);
            return toAppendTo;
        }
    }
    

    然后我们可以在对象映射器中使用这个新类:

    ObjectMapper objectMapper = new ObjectMapper();
    ISO8601DateFormat dateFormat = new ISO8601WithMillisFormat();
    objectMapper.setDateFormat(dateFormat);
    

    我用new Date() 进行了测试,结果是2017-07-24T12:14:26.817Z(以毫秒为单位)。

    【讨论】:

      猜你喜欢
      • 2013-04-18
      • 1970-01-01
      • 2021-11-30
      • 2018-05-10
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多