function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Raj R.Raj R. 

How to display date as mm/dd/yyyy when sending an email through apex class?

Hi,

I am trying to send an email where I include certain values from a customObj1. I noticed that when I insert the field "Start_Date__c" (type is Date) into the email body, then the field renders as "2015-08-12 00:00:00". This is not what I want.

How can I include a Date field that will output as "MM/DD/YYYY" (or MM-DD-YYY) in an email that is sent from an apex classes?
Best Answer chosen by Raj R.
Nisar799Nisar799

Hi rRup,

If you only want to format your date in your current user's locale then you can use below code.
 

Date dt = customObject1.StartDate__c;
String dtStr = dt.format();

OR if you want to keep a fixed date format as "MM/DD/YYYY" then use as
DateTime dt = customObj1.StartDate__c; //Start_Date__c is a date field, No need to worry it will be converted to datetime automatically.
String dtStr = dt.format('MM/dd/yyyy');

In the previos comment you were not getting expected result because 'mm' is for Minutes. So we must use 'MM' for month. 

All Answers

Mudasir WaniMudasir Wani
Hello,

use the below code just in place of myDT use your field.
Datetime myDT = Datetime.now(); // Returns the current Datetime based on a GMT calendar.
String myDate = myDT.format('mm-dd-yyyy'); // formats the date
system.debug('myDate='+myDate);

Please select it as best answer if it solves your problem !!!!!!!!!
Raj R.Raj R.
Hi Mudasir,

That does not work. Below is what i did and the results. Any other thoughts?
 
DateTime dt = customObj1.Start_Date__c; //Start_Date__c is a date field not datetime
String mydate = dt.format('mm-dd-yyyy');

expected value: 7/20/2015 (July 20, 2015)

results : 00-19-2015

 
Nisar799Nisar799

Hi rRup,

If you only want to format your date in your current user's locale then you can use below code.
 

Date dt = customObject1.StartDate__c;
String dtStr = dt.format();

OR if you want to keep a fixed date format as "MM/DD/YYYY" then use as
DateTime dt = customObj1.StartDate__c; //Start_Date__c is a date field, No need to worry it will be converted to datetime automatically.
String dtStr = dt.format('MM/dd/yyyy');

In the previos comment you were not getting expected result because 'mm' is for Minutes. So we must use 'MM' for month. 
This was selected as the best answer