[SalesForce] Format date as two digit month and day

How do you set the .format() method to create a two digit month and day?

I have tried this

myDate.Format('dd/MM/YYYY')

The .format() method has no example of this on the support page.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_date.htm

Here is more of my code so you can see where I am using this:

For(Account_Servicing_Task__c tsk:accTasks){
            //Work through each frequency option.

            //Daily Tasks
            If (tsk.Task_Frequency__c == 'Daily'){
                For(Date d:Weekdays){
                    accActivities.add(new Account_Servicing_Activity__c(
                        Name                        = tsk.Name + ' - ' + d.Format('MM/dd'),
                        Account_Servicing_Task__c   = tsk.Id,
                        Status__c                   = 'Not Started',
                        User__c                     = tsk.Task_Assigned_To__c,
                        Due_Date__c                 = d,
                        Upon_Completion_Notify__c   = tsk.Upon_Completion_Notify__c
                    ));
                }
            }

Best Answer

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.

Related Topic