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 aformat
method that lets you specify what format to use (instead of just the locale default). Likely that is becauseSimpleDateFormat
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 aDatetime
instance with it. I typically do something like:Note if you're calling this code in a loop it may be better to just cache the formatted strings.
Also, a piece of unsolicited advice: use more informative names. Using
d
instead ofday
saves you just two characters, and in my opinion is not worth the tradeoff of additional mental overhead.