tyoshikawa1106のブログ

- Force.com Developer Blog -

SFDC:Apexで週の始まりの日付を取得する方法

Apexで週の始まりの日付を取得したい場合はDateクラスのtoStartOfWeed()メソッドを利用します。


サンプルコードです。

Date myDate = Date.today();
Date weekStart = myDate.toStartofWeek();


週の末尾を取得するメソッドはないのでaddDaysをつかって算出すればいいと思います。


2016年09月25日(日曜日)に実行しました。日本のロケールの場合、SFDCでは週始めは日曜日となっています。
f:id:tyoshikawa1106:20160925204535p:plain


実行コードはこちら。

Date myDate = Date.today();
Date weekStart = myDate.toStartofWeek();

System.debug('本日日付 : ' + myDate);
System.debug('--------------------------------------------');
System.debug('週初日 : ' + weekStart);
System.debug('週初日 + 1 : ' + weekStart.addDays(1));
System.debug('週初日 + 2 : ' + weekStart.addDays(2));
System.debug('週初日 + 3 : ' + weekStart.addDays(3));
System.debug('週初日 + 4 : ' + weekStart.addDays(4));
System.debug('週初日 + 5 : ' + weekStart.addDays(5));
System.debug('週末日 : ' + weekStart.addDays(6));
System.debug('--------------------------------------------');
System.debug('来週日 : ' + weekStart.addDays(7));
System.debug('先週日 : ' + weekStart.addDays(-1));


実行結果です。
f:id:tyoshikawa1106:20160925204704p:plain


予定どおりに取得できました。Apexテストクラスの実装でテストデータを用意するときなどにも便利です。