将 dateTime 中的时间格式从 00:00:00 转换为 23:59:59

时间:2021-02-12 11:57:13

标签: date datetime salesforce apex data-conversion

我已将日期转换为日期时间格式,它以 00:00:00 格式返回小时格式,但我希望它在 23:59:59强>

Date startDate = Date.newInstance(2021,2,1);

这将返回输出为 2021-02-01 00:00:00

当我尝试使用以下代码将其转换为 23:59:59 小时格式时

DateTime startDateConvertTwo = DateTime.newInstance(startDate, Time.newInstance(23, 59, 59, 0));

将日期推到第二天并返回2021-02-02 07:59:59

的值

我试图通过将 Time.newInstance 的值添加为 Time.newInstance(15, 59, 59, 0) 来解决这个问题,这样做我得到了预期的结果。但这是实现我想要做的事情的正确方法吗?

如果有其他方法请告诉我。

1 个答案:

答案 0 :(得分:1)

Date startDate = Date.newInstance(2021,2,1); 的返回输出不是 2021-02-01 00:00:00。它只是一个日期,没有时间信息,但System.debug()将其显示为DateTime,这就是您看到00:00:00的原因。 尝试 System.debug(String.valueOf(startDate)); 仅查看日期部分。


DateTime.newInstance(date, time)

<块引用>

根据本地时区中的指定日期和时间构造一个 DateTime。

如文档所述,您获得的 DateTime 位于您自己的时区。无论如何,System.debug() 以 UTC 时区 (GMT+0) 显示,因此如果您的时区是 GMT-8,您将看到 2021-02-02 07:59:59
System.debug(String.valueOf(startDateConvertTwo )); 将在您自己的时区显示日期时间,因此您会看到 2021-02-01 23:59:59

如果您需要格林威治标准时间的日期时间,您可以使用 DateTime.newInstanceGmt(date, time):

DateTime startDateGMT = DateTime.newInstanceGmt(startDate, Time.newInstance(23, 59, 59, 0));

如果您不能使用该方法,则可以将偏移量添加到 DateTime:

public static DateTime toUTC(DateTime value) {
    Integer offset = UserInfo.getTimezone().getOffset(value);
    return value.addSeconds(offset/1000);
}

您可以在匿名控制台中进行测试:

Date startDate = Date.newInstance(2021,2,1);
DateTime startDateConvertTwo = DateTime.newInstance(startDate, Time.newInstance(23, 59, 59, 0));
DateTime startDateGMT = DateTime.newInstanceGmt(startDate, Time.newInstance(23, 59, 59, 0));
DateTime startDateGMT2 = toUTC(startDateConvertTwo);

System.debug('startDateConvertTwo: ' + startDateConvertTwo); // startDateConvertTwo: 2021-02-01 22:59:59 // Because I'm at GMT+1
System.debug('String.valueOf(startDateConvertTwo): ' + String.valueOf(startDateConvertTwo));  // String.valueOf(startDateConvertTwo): 2021-02-01 23:59:59

System.debug('startDateGMT: ' + startDateGMT); // startDateGMT: 2021-02-01 23:59:59 // Now it's in UTC
System.debug('String.valueOf(startDateGMT): ' + String.valueOf(startDateGMT)); // String.valueOf(startDateGMT): 2021-02-02 00:59:59 // So in my locale time it's the day after,

System.debug('startDateGMT2: ' + startDateGMT2); // startDateGMT2: 2021-02-01 23:59:59 // Same as startDateGMT
System.debug('String.valueOf(startDateGMT2): ' + String.valueOf(startDateGMT2)); // String.valueOf(startDateGMT2): 2021-02-02 00:59:59

public static DateTime toUTC(DateTime value) {
    Integer offset = UserInfo.getTimezone().getOffset(value);
    return value.addSeconds(offset/1000);
}

startDateGMTstartDateGMT2 的输出将相同。

值得注意:日期时间字段以格林威治标准时间存储。在标准 Salesforce UI 中显示时,它们会转换为用户的时区。

相关问题