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

I have tried this


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

1 Answer 1


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:


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.

  • still getting the error: Method does not exist or incorrect signature: void Format(String) from the type Date
    – Matt M
    Mar 22, 2018 at 16:41
  • I have added more of my source code to original post for you.
    – Matt M
    Mar 22, 2018 at 16:46
  • I already updated my answer to address your specific issue.
    – Adrian Larson
    Mar 22, 2018 at 16:47
  • Format method is on DateTime accepts string where as formatMethod on Date doesnt Mar 22, 2018 at 16:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .