I have converted a Date into DateTime format, and it is returning me the hour format in 00:00:00 but I want it to be in 23:59:59

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

This returns the output as 2021-02-01 00:00:00

When I try to convert this to the 23:59:59 hour format by using the below code

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

It is pushing the date to next day and returning the value of 2021-02-02 07:59:59

I tried to sort this out by changing the values of Time.newInstance by adding it as Time.newInstance(15, 59, 59, 0) by doing which I get the expected result. But is it the right way to achieve what I am trying to do?

Please let me know if there are any other ways.

1 Answer 1


You are not considering timezones. Salesforce accepts input of and presents Datetime values in user timezone, but fundamentally stores the values in UTC (GMT).

If you are looking at the output of System.debug(startDateConvertTwo); and you think this is giving you the wrong date/time, that's because System.debug shows the underlying date/time values in UTC (GMT).

I suggest you are in a timezone with offset -8 hours. What you have done in your code is perfectly fine and the resulting Datetime value, if stored in a field or output to the UI in some way (other than via System.debug directly) it will have the value you want.

  • Oh I hadn't taken the timezones into consideration. Thank you for the answer Phil Commented Feb 12, 2021 at 15:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .