私はにデフォルトタイムゾーンが設定されている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
さて、なぜ4行目は値が正しいを持っていますが、タイムゾーンが間違っていますか?それはする必要がありますEurope/Madrid
。そして、(OK、私はそれを許すことができ、Javaの8で廃止された)オフセット、それは0200ではなく、0でなければなりません。
で文字列に変換するときので、それはUTCでlog.info()
SLF4Jは、interferringれ???? または何?ので、私はそうは思いませんSystem.out.println()
UTCあまりにも私を与えます。
私が使用する必要があります知っているOffsetDateTime
が、それはレガシーであり、我々は今のところ、それに日付のすべてのフィールドを変更することはできません。私は、Javaが誤ってそれを解析された理由を知りたいです。
効果は何であるTimezone.getDefault()
のSimpleDateFormatを解析するときは?とのことは何ですかf.getTimezone()
?彼らは、プロセスの異なる部分で行動するように見える.....
内部ジャクソンが使用していますので、私は、この質問をSimpleDateFormat
日付の書式設定/プロセスの日付文字列に。上の設定ではないObjectMapper
影響を与えるSimpleDateFormat
ことマッパーが使用しますか?
私はそれはバグではなく、ラインの誤解だとは思いません。
f.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
result = f.parse(d);
log.info("The result should be 10:34 CEST: {}", result);
どういう意味ですか ?
あなたは、まずあなたがヨーロッパ/マドリッドゾーンの時間を解析しようとしているパーサを伝える、タイムゾーンを設定します。
そして、あなたはそれを表示します。それはあなたのケースでデフォルトのタイムゾーン、UTCで表示しますので、それは、あなたがそれをしたいどの時間帯に推測することはできません。
ご了承ください:
- それはマドリードで午前12時34分ではなく、他の方法でのラウンドだが、それは実際にはUTCで午前10時34分です。
Date.getTimezoneOffset()
さUTCとデフォルトのタイムゾーン間のオフセット(したがって0あなたのケースでは)、あなたはパーサを設定するために使用するタイムゾーンとは何の関係も。また、それは、Java 1.1で廃止されました、あなたは本当にもうそれを使うべきではありません。
異なる時間帯の日付値を表示するために、SimpleDateFormat.format()
例えば、使用することができます。
f.setTimeZone(TimeZone.getTimeZone("UTC"));
log.info("UTC {}", f.format(new Date()));
f.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
log.info("Europe/Madrid {}", f.format(new Date()));