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

Converting the Time format in dateTime from 00:00:00 to 23:59:59

我已将日期转换为 DateTime 格式,它以 00:00:00 返回我的小时格式,但我希望它是 23:59:59

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

这个returns输出为2021-02-0100: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)这样做我得到了预期的结果。但这是实现我想要做的事情的正确方法吗?

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

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


DateTime.newInstance(date, time)

Constructs a DateTime from the specified date and time in the local time zone.

如文档所述,您获得的 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.

如果您需要 GMT 日期时间,您可以使用 DateTime.newInstanceGmt(date, time):

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

如果您不能使用该方法,您可以将您的偏移量添加到日期时间:

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的输出是一样的。

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