【发布时间】:2019-04-18 17:28:45
【问题描述】:
我在 Spring 应用程序中进行了一个简单的测试,它的默认时区设置为 UTC:
@SpringBootApplication
public class MemberIntegrationApp {
@Autowired
private TimeZoneProperties timeZoneProperties;
@PostConstruct
void started() {
TimeZone.setDefault(TimeZone.getTimeZone(timeZoneProperties.getAppDefault())); // which is UTC
}
public static void main(String[] args) {
SpringApplication.run(MemberIntegrationApp.class, args);
}
}
而且,这个简单的测试:(测试类用@SpringBootTest注释来加载主类中的配置,@SpringRunner也被应用)
/**
* Test the effect of setting timezone
*/
@Test
public void testTimezoneSettingOnSimpleDateFormat() throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d = "2018-08-08 12:34:56";
log.info("Trying to parse the date string: {}", d);
Date result = f.parse(d);
log.info("The result should be 12:34 UTC: {}", result);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
result = f.parse(d);
log.info("The result should be 12:34 UTC: {}", result);
f.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
result = f.parse(d);
log.info("The result should be 10:34 CEST: {}", result);
log.info("Now the offset(depre): {}", result.getTimezoneOffset());
}
我有输出:
Trying to parse the date string: 2018-08-08 12:34:56
The result should be 12:34 UTC: Wed Aug 08 12:34:56 UTC 2018
The result should be 12:34 UTC: Wed Aug 08 12:34:56 UTC 2018
The result should be 10:34 CEST: Wed Aug 08 10:34:56 UTC 2018
Now the offset(depre): 0
现在,为什么第四行的值正确,但时区错误?应该是Europe/Madrid。而偏移量(在 Java 8 中已弃用,好吧,我可以原谅),它应该是 +0200,而不是 0。
这是UTC,因为在log.info() 中转换为字符串时,slf4j 会干扰????要不然是啥?我不这么认为,因为System.out.println() 也给了我UTC。
我知道我应该使用OffsetDateTime,但它是遗留的,我们目前无法将所有日期字段更改为该字段。我想知道为什么Java解析错误。
Timezone.getDefault()用SimpleDateFormat解析时有什么作用? f.getTimezone() 是什么?他们似乎在流程的不同部分采取行动.....
我问这个问题,因为杰克逊内部使用SimpleDateFormat 来处理日期字符串/格式化日期。 ObjectMapper 上的配置是否会影响映射器使用的 SimpleDateFormat?
【问题讨论】:
-
我建议你避免使用
SimpleDateFormat类。它不仅过时了,而且出了名的麻烦。今天我们在java.time, the modern Java date and time API 中做得更好。一方面,java.time 在时区之间的转换方面不那么令人困惑。 -
是的……但不是我,而是 Spring/Jackson……你知道的。
标签: java spring-boot datetime java-8 jackson-databind