如何在 Salesforce Apex 中添加天数到日期时间?

How to add days to date time in Salesforce Apex?

您好,我正在使用 Salesforce Apex, 我有一个日期,如下所示。我需要使用 Apex 添加天数。

String dateTime = '2017-07-08T23:59:59Z';

如果我给它加上一天,那么它应该是 2017-07-09T23:59:59Z 作为字符串。我该怎么做?

谢谢!

您需要将字符串转换为 DateTime,然后添加天数。您可以在

之后将其格式化回来
String stringDateTime = '2017-07-08T23:59:59Z';
DateTime dt = DateTime.valueOfGmt(stringDateTime);
DateTime tomorrow = dt.addDays(1);
DateTime nextMonth = dt.addMonths(1);
DateTime anniversary = dt.addYears(1);
String formattedDateTime = dt.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');

注意夏令时问题! "addDays" 函数不支持夏令时,因此如果您在添加天数期间(在有夏令时的时区)跨过夏令时转换,那么时间将会混乱。

要解决此问题,请先将 date/time 拆分为单独的日期和时间部分,将日期添加到日期部分,然后在最后重新组合,如:

DateTime dt = ...;
Integer days = ...;
Date d = dt.date().addDays(days);
Time t = dt.time();
dt = DateTime.newInstance(d, t);

如果您在英国(伦敦)时区工作,以下匿名 Apex 很好地说明了这个问题:

DateTime dt = DateTime.newInstance(2017, 10, 28, 23, 59, 59);
System.debug('Adding days directly: ' + dt.addDays(2));
Date d = dt.date().addDays(2);
Time t = dt.time();
dt = DateTime.newInstance(d, t);
System.debug('Adding days in parts: ' + dt);