Monday, August 10, 2015

Salesforce Date format conversion

I want to change the format of Date field to M/dd/YYYY so it will be read as 07/30/2014.

The field is Date datatype not Datetime datatype.

Note:
1) In Date class there only format() method that will change the date format using locale.
format()
Returns the Date as a string using the locale of the context user
2) Only in DateTime class offer various of date formatting method.
format()
Converts the date to the local time zone and returns the converted date as a formatted string using the locale of the context user. If the time zone cannot be determined, GMT is used.

format(dateFormatString)
Converts the date to the local time zone and returns the converted date as a string using the supplied Java simple date format. If the time zone cannot be determined, GMT is used.

format(dateFormatString, timezone)
Converts the date to the specified time zone and returns the converted date as a string using the supplied Java simple date format. If the supplied time zone is not in the correct format, GMT is used.

formatGmt(dateFormatString)
Returns a Datetime as a string using the supplied Java simple date format and the GMT time zone.

formatLong()
Converts the date to the local time zone and returns the converted date in long date format.

Let say the existing value is from Date datatype, how we can format it.I want the format to be M/dd/yyyy so it return some like this 08/31/2015.

Note based on the code below, we need to convert our Date value to DateTime value using newInstance method like below:


 Date d = myObject__c.Meeting_Date__c;
 Datetime dt=DateTime.newInstance(d.year(), d.month(), d.day());
 reportDate = dt.format('M/dd/yyyy');

No comments:

Post a Comment