LoginSignup
0
1

More than 1 year has passed since last update.

Apexの日付フォーマットの意外な落とし穴

Last updated at Posted at 2022-12-20

Apexで日付を取得する関数がありますが、意外な落とし穴があるので注意が必要です。

結論:正確な日付を出力する場合、年のフォーマットは必ず「yyyy」にしましょう。

簡単な例で説明します。
DateTime nowDate = System.now();
String strDate1 = nowDate.format('yyyy-MM-dd');
String strDate2 = nowDate.format('YYYY-MM-dd');
System.debug('■■■■ Date1 ■■■ ' + strDate1);
System.debug('■■■■ Date2 ■■■ ' + strDate2);

これの実行結果は両方同じです。
17:55:05:013 USER_DEBUG [7]|DEBUG|■■■■ Date1 ■■■ 2022-12-20
17:55:05:013 USER_DEBUG [8]|DEBUG|■■■■ Date2 ■■■ 2022-12-20

次にこれを実行してみましょう
Datetime dt = Datetime.newInstance(2020 , 12, 27, 00, 00, 00);
String strDate1 = dt.format('yyyy-MM-dd');
String strDate2 = dt.format('YYYY-MM-dd');
System.debug('■■■■ Date1 ■■■' + strDate1);
System.debug('■■■■ Date2 ■■■' + strDate2);

フォーマットがYYYYの場合、2021年になりました。
18:05:13:010 USER_DEBUG [15]|DEBUG|■■■■ Date1 ■■■ 2020-12-27
18:05:13:010 USER_DEBUG [16]|DEBUG|■■■■ Date2 ■■■ 2021-12-27

これはApexというより、Javaの仕様によるものです。

年を取得する際、yyyyとYYYYでは取得できる年が異なります。
yyyyはカレンダーの年を取得する。
YYYYは暦週の基準年を取得する。

暦週の基準年は1月1日がある週を基準にしているので、2021年1月1日の週にある2020年12月27日の基準年は2021となります。

実際に私も経験して、大騒ぎにはなりませんでしたが原因がわからず苦労しました。
(元上司が調べてくれて解決しました)

これから年末年始を迎えますが、トラブルにならないようフォーマットをチェックしておきましょうーー

参考URL

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1