Webエンジニア向けプログラミング解説動画をYouTubeで配信中!
▶ チャンネル登録はこちら

【JavaScript ECMAScript】Temporal::Temporal.PlainYearMonth.compare静的メソッドの使い方

Temporal.PlainYearMonth.compare()静的メソッドの使い方について、初心者にもわかりやすく解説します。

作成日: 更新日:

基本的な使い方

Temporal.PlainYearMonth.compare()メソッドは、2つのTemporal.PlainYearMonthオブジェクトの年と月の順序を比較し、その相対的な関係を示す数値を返す静的メソッドです。このメソッドはTemporal.PlainYearMonthクラスに直接所属しており、インスタンスを作成せずに呼び出して使用します。主な目的は、指定された2つの年月がどちらが先か、または同じであるかを効率的に判断することです。

比較の結果は数値で示されます。具体的には、最初の引数で指定された年月が2番目の引数よりも過去の場合には負の整数(例: -1)が返されます。もし両方の引数がまったく同じ年月を表す場合は0が返されます。そして、最初の引数が2番目の引数よりも未来の年月を表す場合には正の整数(例: 1)が返されます。

このメソッドは、引数として2つのTemporal.PlainYearMonthインスタンス、またはTemporal.PlainYearMonthに変換可能なオブジェクト(例えば、ISO 8601形式の文字列 'YYYY-MM')を受け取ります。比較の対象となるのは「年」と「月」の情報のみであり、日、時間、タイムゾーンなどの他の時間要素は比較には影響しません。これにより、日付や期間のソート、特定の年月が別の年月に対して前後関係を判定する処理において、シンプルかつ正確な方法を提供します。

公式リファレンス: Temporal.PlainYearMonth.compare()

構文(syntax)

1const yearMonthA = new Temporal.PlainYearMonth(2023, 10);
2const yearMonthB = new Temporal.PlainYearMonth(2024, 1);
3const comparisonResult = Temporal.PlainYearMonth.compare(yearMonthA, yearMonthB);

引数(parameters)

one, two

  • one: Temporal.PlainYearMonth: 比較対象の最初の年月のインスタンス
  • two: Temporal.PlainYearMonth: 比較対象の2番目の年月のインスタンス

戻り値(return)

Number

Temporal.PlainYearMonth.compare()メソッドは、2つの年月の比較結果を数値で返します。最初の年が2番目の年よりも後の場合、正の数を返します。2つの年が等しい場合、0を返します。最初の年が2番目の年よりも前の場合、負の数を返します。

関連コンテンツ

関連プログラミング言語