LocalDate から java.util.Date への変換とその逆の最も簡単な変換は? [重複] 質問する

LocalDate から java.util.Date への変換とその逆の最も簡単な変換は? [重複] 質問する

LocalDate(Java 8 で導入) をjava.util.Dateオブジェクトに変換する簡単な方法はありますか?

「シンプル」というのは、これよりもシンプルという意味です。

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

それは私にとって少し奇妙に思えます。

日付部分のみに興味があり、どちらのオブジェクトにもタイムゾーン情報はないので、なぜタイムゾーンを明示的に導入するのでしょうか。変換では、深夜の時間とシステムのデフォルトのタイムゾーンが暗黙的に取得される必要があります。

ベストアンサー1

要約

LocalDate(Java 8で導入)をjava.util.Dateオブジェクトに変換する簡単な方法はありますか?「簡単」というのは、これよりも簡単なことを意味します。

いいえ。きちんと、そしてできるだけ簡潔に書きました。

java.util.Date.from(                     // Convert from modern java.time class to troublesome old legacy class.  DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
    myLocalDate                          // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC. 
    .atStartOfDay(                       // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
        ZoneId.of( "America/Montreal" )  // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as “PST”, “CST”, “IST”. 
    )                                    // Produce a `ZonedDateTime` object. 
    .toInstant()                         // Extract an `Instant` object, a moment always in UTC.
)

問題については以下を読んでから考えてください。どうすればもっと簡単にできるでしょうか? デートは何時に始まるかと聞かれたら、「どこで?」と聞く以外にどう答えられるでしょうか? フランスのパリではモントリオール (カリフォルニア州) よりも一日が早く始まり、インディアナ州のコルカタではさらに早く、ニュージーランドのオークランドではさらに早く始まります。すべてが異なる瞬間です。

日付のみの(LocalDate)を日付と時刻に変換するには、しなければならないタイムゾーン ( ZoneId) を適用してゾーン値 ( ZonedDateTime) を取得し、UTC ( Instant) に移動して の定義と一致させますjava.util.Date

詳細

まず、可能な限り、古いレガシーな日付/時刻クラスを避けてくださいjava.util.Date。これらは設計が悪く、混乱を招き、面倒です。これらは、実際には、理由があってjava.timeクラスに置き換えられました。多くの理由。

ただし、必要な場合は、java.time 型と古い型の間で変換できます。古いクラスに追加された新しい変換メソッドを探してください。

Java のすべての日付時刻型 (最新と旧の両方) の表

java.util.Datejava.time.LocalDate

java.util.Dateaは日付を表すので誤称であることに留意してくださいプラスUTCの時刻。対照的に、LocalDateクラスは、時刻とタイムゾーンのない日付のみの値を表します。

からjava.util.Datejava.timeに変換するということは、同等のクラスに変換することを意味しますjava.time.InstantInstantクラスはタイムライン上の瞬間を表しますUTC決議によりナノ秒(小数点以下9桁まで)。

Instant instant = myUtilDate.toInstant();

LocalDateクラスは、時刻とタイムゾーンのない日付のみの値を表します。

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

So we need to move that Instant into a time zone. We apply ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

From there, ask for a date-only, a LocalDate.

LocalDate ld = zdt.toLocalDate();

java.time.LocalDatejava.util.Date

To move the other direction, from a java.time.LocalDate to a java.util.Date means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do not assume that is 00:00:00. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00. Let java.time determine that value by calling atStartOfDay on the LocalDate.

ZonedDateTime zdt = myLocalDate.atStartOfDay( z );

Now extract an Instant.

Instant instant = zdt.toInstant();

Convert that Instant to java.util.Date by calling from( Instant ).

java.util.Date d = java.util.Date.from( instant );

More info


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

どのバージョンの Java または Android でどの java.time ライブラリを使用するかを示す表

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

おすすめ記事