I've noted very strange behaviour in some Apex code I'm running. If I use the Date.ValueOf() function on a datetime. If I then print out the DateTime afterwards the hour/minutes of it have changed to 03:00.

The following code is an example which causes this.

DateTime test1 = System.Now();
System.debug('Hello Test1 BeforeDateValueOf ' + test1);
Date test1Date = Date.ValueOf(test1);
System.debug('Hello Test1 ' + test1);

Prints out the following:

16:19:03:002 USER_DEBUG [2]|DEBUG|Hello Test1 BeforeDateValueOf 2018-07-20 15:19:03 16:19:03:064 USER_DEBUG [4]|DEBUG|Hello Test1 2018-07-20 03:00:00

Why is the time of test1 variable has changed? Surely test1Date is treated separately?

  • Why not just use test1.date()?
    – Adrian Larson
    Jul 20, 2018 at 15:25
  • Is your timezone BST(UTC+1) ? Jul 20, 2018 at 15:32
  • Why are you looking at Time in an object whichw as supposed to store only DATE properly? Jul 20, 2018 at 15:34

1 Answer 1


So your answer lies in Date.ValueOf documentation.

In API version 33.0 or earlier, if you call Date.valueOf with an object that represents a Datetime, the method returns a Date value that contains the hours, minutes, and seconds. In version 34.0 and later, Date.valueOf converts the object to a valid Date without the time information. To convert a variable of type Datetime to a Date, use the Datetime.date method.

We are not supposed to get the time-information in valueOf() in the recent version of API's, thus using it to get time would provide you inconsistent results. The value in timezone we get is for handling the timzone.

Thus your code can use date(); method instead

DateTime test1 = System.Now();
System.debug('Hello Test1 BeforeDateValueOf ' + test1);
Date test1Date = test1.date();
System.debug('Hello Test1 ' + test1);
  • Thank you. This is very helpful and good to know going forward.
    – RedQueries
    Jul 20, 2018 at 16:15

You must log in to answer this question.

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