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
Irina AristovaIrina Aristova 

Format date function returns a wrong date

Irina AristovaFormat date function returns a wrong dateI converted Date time to string in Apex using format function:
DateTime yesterdayDate = Date.today().addDays(-1);
System.Debug(yesterdayDate);
String formattedDate = yesterdayDate.format('MM/dd/yyyy');
System.debug(formattedDate);

The result is:
USER_DEBUG|[24]|DEBUG|2015-05-05 00:00:00
USER_DEBUG|[27]|DEBUG|05/04/2015
I expected to be the same date: 05/05/2015, but it returned 05/04/2015 which is one day earlier
I need to convert date to a string but I am not able because it's returning the wrong date

The user object for me it's set up to:
Time Zone is (GMT-04:00) Eastern Daylight Time (America/New_York)
Locale: Enflish(United States)
Default Time Zone for company is the same as mine: (GMT-04:00) Eastern Daylight Time (America/New_York)
 
Best Answer chosen by Irina Aristova
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi Irina,

Please try below with DateTime.Now() .
 
DateTime yesterdayDate = DateTime.Now().addDays(-1);
System.Debug('-----------'+yesterdayDate);
String formattedDate = yesterdayDate.format('MM/dd/yyyy');
System.debug('-----------'+formattedDate);

Let us know if it helps you.

All Answers

Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi Irina,

Please try below with DateTime.Now() .
 
DateTime yesterdayDate = DateTime.Now().addDays(-1);
System.Debug('-----------'+yesterdayDate);
String formattedDate = yesterdayDate.format('MM/dd/yyyy');
System.debug('-----------'+formattedDate);

Let us know if it helps you.
This was selected as the best answer
Irina AristovaIrina Aristova
Thank you Ashish,
It solved the problem!