Szukaj…


Łatwo znajdź ostatni dzień miesiąca

Jeśli chcesz znaleźć ostatni dzień miesiąca, możesz wykonać skomplikowaną gimnastykę DateTime lub skorzystać z następującej metody.

Powiedz, że chcesz znaleźć ostatni dzień lutego 2021 r. Wykonaj następujące czynności:

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);

Daje to następujące dane wyjściowe w dziennikach:

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

Działa to dla wszystkich metod dodawania, umożliwiając łatwe i szybkie wyszukiwanie DateTimes w przeszłości.



Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow