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

将dateTime中的时间格式从00:00:00转换为23:59:59,date,datetime,salesforce,apex,data-conversion,Date,Datetime,Salesforce,Apex,Data Conversion,我已将日期转换为DateTime格式,它将返回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)

我已将日期转换为DateTime格式,它将返回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

Date startDate = Date.newInstance(2021,2,1);
我试图通过更改Time.newInstance的值来对其进行排序,将其添加为Time.newInstance(15,59,59,0),从而得到预期的结果。但是,这是实现我想要做的事情的正确途径吗


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

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

尝试
System.debug(String.valueOf(startDate))
仅查看日期部分


从本地时区中指定的日期和时间构造DateTime

正如文档所述,您得到的日期时间在您自己的时区内。无论如何
System.debug()
以UTC时区(GMT+0)显示,因此如果您的时区是GMT-8,您将看到
2021-02-02 07:59:59

System.debug(String.valueOf(startdateconvertwo))将显示您所在时区的日期时间,因此您将看到
2021-02-01 23:59:59

如果需要以GMT表示的日期时间,可以使用
DateTime.newInstanceGmt(日期,时间)

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

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);
}
startDateGMT
startDateGMT2
的输出将相同


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

感谢您提供详细答案。