简体   繁体   English

Java / Kotlin:为什么Jackson解析日期与SimpleDateFormat不同?

[英]Java/Kotlin: Why does Jackson parse dates differently from SimpleDateFormat?

I'm sure this is some form of user error, but I can't puzzle out what I'm doing incorrectly. 我确定这是某种形式的用户错误,但我无法弄清楚我做错了什么。

I have a Kotlin data class that with a constructor field like this: 我有一个Kotlin数据类,其构造函数字段如下:

data class CronEvent(
    @JsonFormat(
            shape = JsonFormat.Shape.STRING,
            pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'"
    )
    @JsonProperty("time")
    val time: Date
 )

This gets populated by ObjectMapper that accepts a json string as a payload. 这由ObjectMapper填充,它接受json字符串作为有效负载。 For my unit test, I have a SimpleDateFormat object that I instantiate with the same pattern. 对于我的单元测试,我有一个SimpleDateFormat对象,我使用相同的模式进行实例化。

val jsonStream = CronEventTests::class.java.classLoader.getResourceAsStream("CronEventPayload.json")
val cronEvent = jsonStreamToCronEvent(jsonStream)
// ...
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
val expectedDate = simpleDateFormat.parse("2018-01-15T00:48:43Z")
cronEvent.time shouldBe expectedDate

The json file ( CronEventPayload.json ) that I load in my unit test has the exact same date string ( 2018-01-15T00:48:43Z ) yet my test fails. 我在单元测试中加载的json文件( CronEventPayload.json )具有完全相同的日期字符串( 2018-01-15T00:48:43Z )但我的测试失败了。

java.lang.AssertionError: expected: Mon Jan 15 00:48:43 MST 2018 but was: Sun Jan 14 17:48:43 MST 2018
Expected :Mon Jan 15 00:48:43 MST 2018 
Actual   :Sun Jan 14 17:48:43 MST 2018

They have the same input and are utilizing the same date format string, but they're clearly different. 它们具有相同的输入并且使用相同的日期格式字符串,但它们明显不同。 Why are these two dates not the same? 为什么这两个日期不一样?

The default timezone for @JsonFormat is UTC . @JsonFormat的默认时区是UTC You can override with the timezone attribute of the annotation. 您可以使用注释的timezone属性覆盖。

The default timezone for SimpleDateFormat is your local timezone ( MST , reading from your output) SimpleDateFormat的默认时区是您的本地时区( MST ,从您的输出读取)

Make sure that the timezones match. 确保时区匹配。 You can add the line: 您可以添加以下行:

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

just below the construction of your SimpleDateFormat . 就在SimpleDateFormat的构造之下。

Although your dates in their text format contains the timezone (the Z at the end, meaning UTC ), you're using a format that just treats the Z as a literal character, you're not interpreting it as a timezone. 虽然您的文本格式的日期包含时区(结尾处的Z ,表示UTC ),但您使用的格式只是将Z视为文字字符,您不会将其解释为时区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM