Datetime.format() convert the Datetime to your local time zone, while a System.debug() of a Datetime always shows it in ISO format UTC (GMT+0).
Since New York is at GMT-5, if the Datetime in UTC is between 00:00 and 04:59, calling .format()
method will return the day before.
In order to get the same date you see by System.debug(Datetime), you have to use .formatGMT
Example:
Datetime d1 = System.now();
String sFormat = d1.format('yyyy/MM/dd HH:mm:ss');
String sFormatGMT = d1.formatGMT('yyyy/MM/dd HH:mm:ss');
System.debug(d1); // DEBUG|2020-01-06 11:13:21 because it always shows the datetime in UTC
System.debug(sFormat); // DEBUG|2020/01/06 12:13:21 because I'm at GMT+1
System.debug(sFormatGMT); // DEBUG|2020/01/06 11:13:21 because I forced the GMT time zone
If you want to convert the date to a specific time zone you could use .format(String pattern, String timezone)
. The documentation states:
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.
About the timezone parameter you should use the full name, not the abbreviation (emphasis mine):
Valid time zone values for the timezone argument are the time zones of
the Java TimeZone class that correspond to the time zones returned by
the TimeZone.getAvailableIDs method in Java. We recommend you use
full time zone names, not the three-letter abbreviations.