私は最近2年間でSimpleDateFormat
を正常に使用しています。私はそれを使用して、時間の束を構築しました。SimpleDateFormatからDateTimeFormatterに移動するときの問題
SimpleDateFormat
(SDF)のスレッドセーフではない問題に遭遇したので、私は最後にこのユーティリティクラスをリファクタリングしてDateTimeFormatter
(DTF)を内部的に使用しました。両方のクラスの時間パターンはほぼ同じなので、この移行は当時は良い考えでした。
EpochMillis
(ミリ秒:1970-01-01T00:00:00Z
からのミリ秒)の取得で問題が発生しました。 10:30
をHH:mm
として解釈し、1970-01-01T10:30:00Z
と解釈すると、DTFは同じことをしません。 DTFはを使用してLocalTime
を解析できますが、EpochMillis
を取得するために必要なZonedDateTime
は解析できません。
私はjava.time
のオブジェクトが異なる考え方に従っていることを理解しています。 Date
,Time
、およびZoned
のオブジェクトは別々に保管されます。しかし、私のユーティリティクラスがこれまでと同じようにすべての文字列を解釈するためには、欠落しているすべてのオブジェクトのデフォルトの解析を動的に定義できる必要があります。私は使用しようとしました
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.parseDefaulting(ChronoField.YEAR, 1970);
builder.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1);
builder.parseDefaulting(ChronoField.DAY_OF_MONTH, 1);
builder.parseDefaulting(ChronoField.HOUR_OF_DAY, 0);
builder.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0);
builder.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0);
builder.append(DateTimeFormatter.ofPattern(pattern));
しかし、これはすべてのパターンでは機能しません。 pattern
で定義されていないパラメータのデフォルトのみを許可しているようです。 ChronoField
がpattern
で定義されているかどうかをテストする方法はありますか?
代わりに、私はどちらかのすべてのケースをカバーしていない
TemporalAccessor temporal = formatter.parseBest(time,
ZonedDateTime::from,
LocalDateTime::from,
LocalDate::from,
LocalTime::from,
YearMonth::from,
Year::from,
Month::from);
if (temporal instanceof ZonedDateTime)
return (ZonedDateTime)temporal;
if (temporal instanceof LocalDateTime)
return ((LocalDateTime)temporal).atZone(formatter.getZone());
if (temporal instanceof LocalDate)
return ((LocalDate)temporal).atStartOfDay().atZone(formatter.getZone());
if (temporal instanceof LocalTime)
return ((LocalTime)temporal).atDate(LocalDate.of(1970, 1, 1)).atZone(formatter.getZone());
if (temporal instanceof YearMonth)
return ((YearMonth)temporal).atDay(1).atStartOfDay().atZone(formatter.getZone());
if (temporal instanceof Year)
return ((Year)temporal).atMonth(1).atDay(1).atStartOfDay().atZone(formatter.getZone());
if (temporal instanceof Month)
return Year.of(1970).atMonth((Month)temporal).atDay(1).atStartOfDay().atZone(formatter.getZone());
を試してみました。
動的な日付/時刻/日付/時刻/ゾーンの日付/時刻解析を有効にするための最良の方法を教えてください。
問題がスレッドセーフであった場合、なぜソリューションは 'synchronized'ブロックの形式へのアクセスを保護していませんでしたか? – BadZen
はい、元の問題は本当にスレッドセーフであっただけです。しかし、私は時間を浪費していました。実際には動作させるのが好きです。一般的な解析のデフォルト設定は 'java.time'では不可能だとは思いません。 – dotwin
現時点では、この時点で沈んでいるようですが、正直なところ...現地時間にゾーンを適用してから、エポックからミリ秒を測定することができます: 'ZonedDateTime zdt = local.atZone(ZoneId.of(" America/New_York "));'しかし、複雑さを追加するようなことはないようです。 – BadZen