The reason of such behavior is daylight saving time offset.
You are doing everything okay. Result is expected with Datetime
class. Your user's timezone is America/Chicago
. According to Daylight Saving Time Changes 2018 article, 4-th of November was a day, when clock went back 1 hour.
Sunday, 4 November 2018, 02:00:00 clocks were turned backward 1 hour to
Sunday, 4 November 2018, 01:00:00 local standard time instead.
I have simplified your code to the following.
Datetime myDateTime = Datetime.newInstance(2018, 11, 4);
//DEBUG|myDateTime.format(yyyy-MM-dd HH:mm:ss):2018-11-04 00:00:00
System.debug('myDateTime.format(yyyy-MM-dd HH:mm:ss):' + myDateTime.format('yyyy-MM-dd HH:mm:ss'));
//DEBUG|myDateTime.formatGMT(yyyy-MM-dd HH:mm:ss):2018-11-04 05:00:00
System.debug('myDateTime.formatGMT(yyyy-MM-dd HH:mm:ss):' + myDateTime.formatGMT('yyyy-MM-dd HH:mm:ss'));
Datetime newDateTime = myDateTime.addDays(1);
//DEBUG|newDateTime.format(yyyy-MM-dd HH:mm:ss):2018-11-04 23:00:00
System.debug('newDateTime.format(yyyy-MM-dd HH:mm:ss):' + newDateTime.format('yyyy-MM-dd HH:mm:ss'));
//|DEBUG|newDateTime.formatGMT(yyyy-MM-dd HH:mm:ss):2018-11-05 05:00:00
System.debug('newDateTime.formatGMT(yyyy-MM-dd HH:mm:ss):' + newDateTime.formatGMT('yyyy-MM-dd HH:mm:ss'));
Datetime myDateTime = Datetime.newInstance(2018, 11, 4);
here you constructing local Chicago time 4-th of November 00:00:00
after 2 hours, it is 02:00:00
and immediately time goes back 1 hour and it becomes 01:00:00
time. So you have not 24 hours per day, but 25.
Looks like Datetime.addDays(1)
method adds 24 hours to Datetime
object and that is why after myDateTime.addDays(1)
you have 2018-11-04 23:00:00
. If you add 25 hours to it, you will get expected 2018-11-05 00:00:00
and Monday
result.
What final conclusion I did from the current case.
If you don't have to work with/get/manipulate with hours, minutes and seconds - always use Date class. Because it adds days correctly with all daylight saving time offsets.
Date myDate = Date.newInstance(2018, 11, 4);
//DEBUG|myDate.format(yyyy-MM-dd):11/4/2018
System.debug('myDate.format(yyyy-MM-dd):' + myDate.format());
Date newMyDate = myDate.addDays(1);
//DEBUG|newMyDate.format:11/5/2018
System.debug('newMyDate.format:' + newMyDate.format());
DateTime newMyDateTime = DateTime.newInstance(newMyDate.year(), newMyDate.month(), newMyDate.day());
//newMyDateTime.format(yyyy-MM-dd HH:mm:ss):2018-11-05 00:00:00
System.debug('newMyDateTime.format(yyyy-MM-dd HH:mm:ss):' + newMyDateTime.format('yyyy-MM-dd HH:mm:ss'));
//DEBUG|newMyDateTime.format(EEEE):Monday
System.debug('newMyDateTime.format(EEEE):' + newMyDateTime.format('EEEE'));
from upper snippet, we convert Date
to Datetime
at the latest step, where we need to know what is a day of the week. But all manipulations we did with Date
class