trigger ScratchTrigger on Case (before insert) {
//Write a trigger that will prevent each user from creating more than 99 cases a month
//Create values for this month
Date dayToday = Date.Today();
DateTime firstDayOfMonth = DateTime.newInstance(daytoday.toStartOfMonth().addMonths(-1), Time.newInstance(0,0,0,0));
DateTime lastDayOfMonth = DateTime.newInstance(dayToday.addMonths(1).toStartofMonth().addDays(-1)), Time.newInstance(0,0,0,0));
system.debug('Todays Date = '+dayToday+ ' firstDayOfMonth = '+firstDayOfMonth+ ' lastday of Month = '+lastDayOfMonth);
//When a new case is crated, iterate through Trigger.New and add case to UserCreated Cases
if(Trigger.isInsert){
List<Case> UserCreatedCases = [SELECT Id, CreatedById, CreatedDate FROM Case WHERE (CreatedDated >= :firstDayOfMonth) AND (CreatedDate <= :lastDayOfMonth)];
}
}
Hi Upton,By Date Method: Date firstDayOfMonth = System.today().toStartOfMonth();
To get the last day of the month:
Date lastDayOfMonth = firstDayOfMonth.addDays(Date.daysInMonth(firstDayOfMonth.year(), firstDayOfMonth.month()) - 1);
The output would be:
11:00:44:005 USER_DEBUG [5]|DEBUG|firstDayOfMonth 2021-02-01 00:00:00 11:00:44:005 USER_DEBUG [6]|DEBUG|lastDayOfMonth 2021-02-28 00:00:00
By DateTime Method:
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);
The output would be;
11:00:44:005 USER_DEBUG [15]|DEBUG|2021-02-28 11:00:00
11:00:44:005 USER_DEBUG [16]|DEBUG|28
you can modify this as per your requirements.
If you found this answer helpful mark this as best answers to help others.