SimpleDateFormatのガイド

SimpleDateFormatのガイド

1. 前書き

このチュートリアルでは、in-depth tour of the SimpleDateFormat classを使用します。

simple instantiationand formatting stylesと、クラスがhandling locales and time zonesに対して公開する便利なメソッドを見ていきます。

さて、始める前に、SimpleDateFormat isはスレッドセーフではないことに注意しましょう。 したがって、並行環境で適切な予防措置を取ることは開発者に任されています。

2. 単純なインスタンス化

まず、新しいSimpleDateFormat objectをインスタンス化する方法を見てみましょう。

4 possible constructorsがありますが、名前に合わせて、物事を単純にしましょう。 開始するために必要なのは、String representation of a date pattern we wantだけです。

次のようなダッシュで区切られた日付パターンから始めましょう。

"dd-MM-yyyy"

これにより、現在の月の日付、現在の年の月、最後に現在の年から始まる日付が正しくフォーマットされます。 単純な単体テストで新しいフォーマッタをテストできます。 新しいSimpleDateFormat objectをインスタンス化し、既知の日付を渡します。

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
assertEquals("24-05-1977", formatter.format(new Date(233345223232L)));

上記のコードでは、formatterはミリ秒をlong として人間が読める日付(1977年5月24日)に変換します。

2.1. ファクトリーメソッド

SimpleDateFormatは、日付フォーマッターをすばやく作成するための便利なクラスですが、we’re encouraged to use the factory methods on the DateFormat classgetDateFormat()getDateTimeFormat()getTimeFormat()です。

これらのファクトリメソッドを使用する場合、上記の例は少し異なります。

DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT);
assertEquals("5/24/77", formatter.format(new Date(233345223232L)));

上記からわかるように、フォーマットオプションの数は、fields on the DateFormat classによって事前に決定されています。 これは主にrestricts our available options for formattingであるため、この記事ではSimpleDateFormat に固執します。

3. 日付の解析

SimpleDateFormat DateFormat は、日付をフォーマットできるだけでなく、操作を逆にすることもできます。 parse メソッドを使用すると、同等のinput the String representation of a date and return the Date objectを実行できます。

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = new Date(233276400000L);
Date parsedDate = formatter.parse("24-05-1977");
assertEquals(myDate.getTime(), parsedDate.getTime());

ここで重要なのは、pattern supplied in the constructor should be in the same format as the date parsedparse メソッドを使用していることです。


4. 日時パターン

SimpleDateFormat は、日付をフォーマットするときにさまざまなオプションを提供します。 完全なリストはJavaDocsで利用できますが、より一般的に使用されるオプションのいくつかを見てみましょう。

文字

日付コンポーネント

M

12; 12月

y

year

94

d

day

23;月曜日

H

hour

03

m

57

String内のoutput returned by the date component also depends heavily on the number of characters used。 たとえば、6月を考えてみましょう。 日付文字列を次のように定義する場合:

"MM"

その後、結果は番号コード06として表示されます。 ただし、日付文字列に別のMを追加した場合:

"MMM"

次に、結果のフォーマットされた日付が単語Junとして表示されます。

5. ロケールの適用

SimpleDateFormat classもsupports a wide range of localesであり、コンストラクターが呼び出されたときに設定されます。

日付をフランス語でフォーマットして、これを実践しましょう。 コンストラクターにLocale.FRANCE を提供しながら、SimpleDateFormat オブジェクトをインスタンス化します。

SimpleDateFormat franceDateFormatter = new SimpleDateFormat("EEEEE dd-MMMMMMM-yyyy", Locale.FRANCE);
Date myWednesday = new Date(1539341312904L);
assertTrue(franceDateFormatter.format(myWednesday).startsWith("vendredi"));

水曜日の午後という特定の日付を指定することで、franceDateFormatter hasが日付を正しくフォーマットしたと断言できます。 新しい日付は正しくVendredi で始まります-水曜日のフランス語!

Locale version of the constructorwhilst many locales are supported, full coverage is not guaranteedのちょっとした落とし穴に注意する価値があります。 ロケールを確実にカバーするために、DateFormat classでファクトリメソッドを使用することをお勧めします。

6. タイムゾーンの変更

SimpleDateFormat DateFormat classを拡張するため、manipulate the time zone using the setTimeZone methodも使用できます。 これを実際に見てみましょう。

Date now = new Date();

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE dd-MMM-yy HH:mm:ssZ");

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
logger.info(simpleDateFormat.format(now));

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
logger.info(simpleDateFormat.format(now));

上記の例では、同じSimpleDateFormatオブジェクトの2つの異なるタイムゾーンに同じDate を提供しています。 ‘Z' character to the end of the pattern String to indicate the time zone differencesも追加しました。 次に、format メソッドからの出力がユーザー用にログに記録されます。

実行すると、2つのタイムゾーンに対する現在の時刻が表示されます。

INFO: Friday 12-Oct-18 12:46:14+0100
INFO: Friday 12-Oct-18 07:46:14-0400

7. 概要

このチュートリアルでは、SimpleDateFormatの複雑さについて深く掘り下げました。

instantiate SimpleDateFormat の方法とpattern String impacts how the date is formattedの方法を見てきました。

最終的にusing time zonesを試す前に、出力文字列のchanging the localesを試してみました。

いつものように、完全なソースコードはover on Githubで見つけることができます。