2

Is there a reason that the below returns 2017-11-30? I know changing it to Datetime.newInstance fixes it, but I'm mostly wondering why this happens.

Datetime myDate = Date.newInstance(2017, 12, 1);
system.debug(myDate.format('yyyy-MM-dd'));
5

mplax,

when you create the date via Date.newInstance it is creating the 1st of dec as per GMT.

Once you call format on it. It applies your locale settings which would not be as GMT and your timezone might be behind GMT by few hours. So it is showing you 30th Nov.

E.g. If you add few hours to it then it will start showing the date you expected. The hours that you might to add is based on what is the offset of your timezone with the GMT.

enter image description here

2
  • Very interesting. I wonder if there's ever a time when this is preferred behavior... Thanks for your help!
    – mplax
    May 14 '18 at 21:16
  • @mplax There is a format date option that keeps the time in GMT so that it wont apply your custom locale as well: datetime.formatGMT(dateFormatString)
    – gNerb
    May 14 '18 at 22:03

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.