Memos About Salesforce

Salesforceにハマってたこと!

日付 月初・月末 求めたい時

こんにちは、管理人の@Salesforce.Zです。

日付の計算や比較は

開発する際に避けれないものか

と考えております。

今回、日付の月初を求めるため

色々なサンプルを提供させていただきます。

最後まで付き合ってください。

意見も待っております。



目次


月初

現在日付の月初

現在の日付:2018年07月21日とする

・E.X. Code

// 実コード
Date currentDate = Date.Today();
Date curFirstDay = currentDate.toStartOfMonth();

// デバッグ確認
System.debug('===========================');
System.debug('■■■ currentDate-->' + currentDate);
System.debug('■■■ curFirstDay-->' + curFirstDay);
System.debug('===========================');

・出力結果

f:id:jude2016:20180721150020p:plain

先月の月初

・E.X.コード

// 実コード
Date currentDate = Date.Today();
Date lastMon = currentDate.addMonths(-1);
Date lastMonFirstDay = lastMon.toStartOfMonth();

// デバッグ確認
System.debug('===========================');
System.debug('■■■ currentDate-->' + currentDate);
System.debug('■■■ lastMonFirstDay-->' + lastMonFirstDay);
System.debug('===========================');

・出力結果

f:id:jude2016:20180721150342p:plain

翌月の月初

・E.X.コード

// 実コード
Date currentDate = Date.Today();
Date nextMon = currentDate.addMonths(1);
Date nextMonFirstDay = nextMon.toStartOfMonth();

// デバッグ確認
System.debug('===========================');
System.debug('■■■ currentDate-->' + currentDate);
System.debug('■■■ nextMonFirstDay-->' + nextMonFirstDay);
System.debug('===========================');

・出力結果
f:id:jude2016:20180721150625p:plain

月末

現在日付の月末

現在の日付:2018年07月21日とする

月の最終日を確認する最も簡単な方法は、

翌月の最初の日を調べ、

そこから 1 日差し引くことです。

・E.X.コード

// 実コード
Date currentDate = Date.Today();
Date nextMon = currentDate.addMonths(1);
Date nextMonFirstDay = nextMon.toStartOfMonth();
Date currentLastDay = nextMonFirstDay.addDays(-1);
// デバッグ確認
System.debug('===========================');
System.debug('■■■ currentDate-->' + currentDate);
System.debug('■■■ currentLastDay-->' + currentLastDay);
System.debug('===========================');

・出力結果
f:id:jude2016:20180721151423p:plain

先月の月末

・E.X.コード

// 実コード
Date currentDate = Date.Today();
Date currenMonFirstDay = currentDate.toStartOfMonth();
Date currentLastMonLastDay = currenMonFirstDay.addDays(-1);
// デバッグ確認
System.debug('===========================');
System.debug('■■■ currentDate-->' + currentDate);
System.debug('■■■ currentLastMonLastDay-->' + currentLastMonLastDay);
System.debug('===========================');

・出力結果
f:id:jude2016:20180721151640p:plain

翌月の月末

・E.X.コード

// 実コード
Date currentDate = Date.Today();
Date next2Mon = currentDate.addMonths(2);
Date next2MonFirstDay = next2Mon.toStartOfMonth();
Date nextMonLastDay = next2MonFirstDay.addDays(-1);
// デバッグ確認
System.debug('===========================');
System.debug('■■■ currentDate-->' + currentDate);
System.debug('■■■ nextMonLastDay-->' + nextMonLastDay);
System.debug('===========================');

・出力結果
f:id:jude2016:20180721151840p:plain

いかがでしょうか
大したことではないが、以上です。