轻松找到一个月的最后一天

如果你需要找到该月的最后一天,你可以进行复杂的 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);

这会在日志中生成以下输出:

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

这适用于所有添加方法,使你可以轻松快速地找到过去的日期时间。