I have a simple test in a Spring application, which has default timezone set to 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);
}
}
And, this simple test: (The test class is annotated with @SpringBootTest to load the configuration in main class and @SpringRunner is applied, too)
/**
* 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());
}
I have output:
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
Now, why the fourth line has the value correct, but the timezone is wrong? It should be Europe/Madrid. And the offset(which is deprecated in Java 8, OK I can forgive it), it should be +0200, not 0.
It is UTC because when converting to string in log.info(), slf4j is interferring???? Or what? I don't think so because System.out.println() gives me UTC too.
I know I should use OffsetDateTime, but it is legacy and we cannot change all fields of date to that, for now. I want to know why Java parsed it wrongly.
What is the effect of Timezone.getDefault() when parsing with SimpleDateFormat? And what is that of f.getTimezone()? They seem to act in different part of the process.....
I ask this question, because internally Jackson uses SimpleDateFormat to process date string/formatting dates. Does the config on an ObjectMapper affect the SimpleDateFormat that the mapper uses?
