2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Salesforce] [Apex] 月初、月末を取得する

Last updated at Posted at 2021-09-02

はじめに

Apexで月初とか月末を出す処理、何かと使うので自分の備忘録として載せておきます。

月初の日付取得

DateクラスにtoStartOfMonthメソッドが用意されているのでそれを呼ぶだけです。

Date targetDate = Date.today();
Date startDate = targetDate.toStartOfMonth();

月末の日付取得

DateクラスにtoEndOfMonthメソッドが存在しないので自分で実装しないといけません。

public static date getEndOfMonth(Date targetDate) {
    Date NewTargetDate = targetDate.addMonths(1).toStartOfMonth();
    Date result = NewTargetDate - 1;   
    return result;
}

次月の初月を取得した後に1日引き算する方法で実現する手法です。
自分が新人だったときVB5で同じことしていました。20年前から変わっていないです。もはや伝統芸。

文献

Dateクラス 公式ドキュメント
https://developer.salesforce.com/docs/atlas.ja-jp.apexcode.meta/apexcode/apex_methods_system_date.htm

2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?