サーチ…


1か月の最後の日を簡単に見つける

月の最後の日を探す必要がある場合は、複雑なDateTimeの体操をすることも、次の方法を使用することもできます。

2021年2月の最終日を検索したいとします。次の操作を行います。

Integer month = 2;
Integer day = null;
Integer year = 2021;

// Create a new DateTime object for the first day of the month following
// the date you're looking for.
DateTime dtTarget = DateTime.newInstance(year, month, 1);
//In this case we would be sure that month would not be out of bound
dtTarget = dtTarget.addMonths(1);
// Then use the .addDays() method to add negative 1 days. This gives you
// the last day of the target month.
DateTime lastDayOfMonth = dtTarget.addDays(-1);
day = lastDayOfMonth.day();

System.debug(lastDayOfMonth);
System.debug(day);

これにより、Logsに次の出力が生成されます。

18:19:57:005 USER_DEBUG [15]|DEBUG|2021-02-28 08:00:00
18:21:10:003 USER_DEBUG [16]|DEBUG|28

これはすべてのaddメソッドで機能し、過去のDateTimesを簡単かつ迅速に見つけることができます。



Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow