-1

I'm trying to convert my datetime value into MM.DD.YYYY format

Tried the following,

1. 
datetime dt = system.today();

string f = DateTime.newInstance(
        dt.year(), dt.month(), dt.day()
    ).format('MM.DD.YYYY');
system.debug(f);
==> result: 05.133.2020 , expected result: 05.13.2020


2. 
datetime dt = system.today();
system.debug('d:'+dt.format('MM.DD.YYYY'));
==> result: 05.133.2020 , expected result: 05.13.2020

I know I could something like the following,

datetime d = system.today();
string s = d.month()+ '.' + d.day() + '.' + d.year();
system.debug(s);

But want to see why the format method is not working.

Please let me know what did I miss here?

  • .format('MM.dd.YYYY') with DD you are asking for the day of the year, which is 133. Salesforce uses the format from Java – Sergio Alcocer May 14 at 5:43
  • thanks for the answer. It worked. does the letter case matter in format method? – Anurag May 14 at 5:45
  • I think you would like to use also yyyy instead. that gives you the year and not the week year – Sergio Alcocer May 14 at 5:55
1

According to the documentation

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.

...

Usage

For more information on the Java simple date format, see Java SimpleDateFormat.

According to that link

D: Day in year

d: Day in month

y: Year

Y: Week year

So your format should be

.format('MM.dd.yyyy');
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.