java 时区错乱,设置了时区的SimpleDateFormat获取正确的值,但时区错误

我在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,是因为当转换为in时log.info(),slf4j会干扰吗?要不然是啥?我不这么认为,因为也System.out.println()给我UTC。

我知道我应该使用OffsetDateTime,但是这是遗留的,我们暂时无法将所有日期字段更改为该字段。我想知道为什么Java错误地解析了它。

Timezone.getDefault()使用SimpleDateFormat进行解析有什么作用?那是什么f.getTimezone()呢?他们似乎在流程的不同部分起作用。

我问这个问题,因为在内部Jackson

SimpleDateFormat用来处理日期字符串/格式日期。配置是否ObjectMapper影响SimpleDateFormat映射器使用的?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值