【问题标题】:Accessing original local time from Joda DateTime object从 Joda DateTime 对象访问原始本地时间
【发布时间】:2015-02-17 18:26:55
【问题描述】:

我有以下 JSON 字符串正在转换为 Joda DateTime 对象(使用 Jackson)

"2015-08-02T11:30:00.000+01:00"

使用下面的代码打印出时间

DateTimeFormatter timeFmt = DateTimeFormat.forPattern("HH:mm");
String timePart = timeFmt.print(dt);

我明白了:

10:30

哪个是正确的 UTC 时间。

但是我希望能够打印出原来的当地时间

11:30

我怎样才能从我的日期时间对象中得到这个(甚至是 +01:00 的原始偏移量)?

谢谢,

肯尼

【问题讨论】:

  • 如何转换成DateTime?您可以将您的序列化程序添加到您的问题中吗?
  • 很抱歉没有尽快回复您,我正在度假。我正在使用 Spring restTemplate.exchange,它在后台使用 Jackson 进行反序列化。我相信我需要为 Jackson 添加一个自定义对象映射器来处理 dateTime,因为默认情况下会丢失本地时间信息并仅转换为 UTC。我还没有这样做,但现在会尝试这样做,并在我完成后更新。

标签: json timezone jackson deserialization jodatime


【解决方案1】:

好的,我终于找到了解决方案。这不是最优雅的,我宁愿在应用程序 context.xml 中注册自定义对象映射器,但无法使其正常工作..

无论如何,我在反序列化期间返回 UTC 的原因是 Jackson 提供的 DateTime 反序列化器故意这样做:

public ReadableInstant deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException
    {
        JsonToken t = jp.getCurrentToken();
        if(t == JsonToken.VALUE_NUMBER_INT)
            return new DateTime(jp.getLongValue(), DateTimeZone.UTC);
        if(t == JsonToken.VALUE_STRING)
        {
            String str = jp.getText().trim();
            if(str.length() == 0)
                return null;
            else
                return new DateTime(str, DateTimeZone.UTC);
        } else
        {
            throw ctxt.mappingException(getValueClass());
        }
    }

所以我创建了一个自定义对象映射器

public class CustomObjectMapper extends ObjectMapper {

public CustomObjectMapper() {
    SimpleModule module = new SimpleModule("DateTime", Version.unknownVersion());
    module.addDeserializer(DateTime.class, new dateDeserializer());
    super.registerModule(module);
}

public class dateDeserializer extends JsonDeserializer<DateTime> {

    @Override
    public DateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

  JsonToken t = jp.getCurrentToken();
  String str = jp.getText().trim();
  if (str.length() == 0) {
    return null;
  }
  else {
    DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withOffsetParsed();
    return formatter.parseDateTime(str);
  }
    }

}

}

然后用其余模板注册这个

private MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter() {
    MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
    converter.setObjectMapper(new CustomObjectMapper());
    return converter;
}

restTemplate.getMessageConverters().add(0, mappingJacksonHttpMessageConverter());

如果有人对此有任何改进或想法,很想听听。

谢谢,

肯尼

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多