Поиск…


Легко найти последний день месяца

Если вам нужно найти последний день месяца, вы можете сделать сложную гимнастику DateTime или использовать следующий метод.

Скажем, вы хотите найти последний день февраля 2021 года. Сделайте следующее:

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

Это работает для всех методов добавления, позволяющих легко и быстро находить DateTimes в прошлом.



Modified text is an extract of the original Stack Overflow Documentation
Лицензировано согласно CC BY-SA 3.0
Не связан с Stack Overflow