Check out salesforce documentation on their Date class.
The method you are looking for is daysInMonth(...)
Integer numberOfDays = Date.daysInMonth(dateField.year(), dateField.month());
Date lastDayOfMonth = Date.newInstance(dateField.year(), dateField.month(), numberOfDays);
Keep in mind "dateField" above is a place holder for any Date variable or field you want to go off.
Only the Datetime
type has a format
method that lets you specify what format to use (instead of just the locale default). Likely that is because SimpleDateFormat
supports many time components in addition to date values.
You would just use the month and day elements. For example, this format would yield '03/22'
for today:
Datetime.now().format('MM/dd')
If you already have a Date
instance and want to format it, instantiate a Datetime
instance with it. I typically do something like:
Datetime.newInstance(myDate, Time.newInstance(12, 0, 0, 0)).format('...')
Note if you're calling this code in a loop it may be better to just cache the formatted strings.
List<String> formattedWeekdays = new List<String>();
Time noon = Time.newInstance(12, 0, 0, 0);
for (Date day : weekDays)
formattedWeekdays.add(Datetime.newInstance(day, noon).format('MM/dd'));
Also, a piece of unsolicited advice: use more informative names. Using d
instead of day
saves you just two characters, and in my opinion is not worth the tradeoff of additional mental overhead.
Best Answer
You can utilize a method like this in your controller to append the suffix to the day portion of the date, but this approach won't work directly in VF using an
<apex:param />
input into a formatter. You'll have to construct the date string in the controller.Caveat: this code doesn't work as written for integer values greater than 100 - but there are few months with more than 100 days, so I figured it was safe enough as written.
Update
Here's some example controller code and VF markup
VF
Apex