Datetime conversion of a custom datetime field to a date value doesn't work correctly. This behavior isn't explained in Salesforce's documentation as far as I know.
- Set your org & user to Pacific time zone.
- Create a new Datetime field, ExpirationDate__c on Product2.
- On an existing or new product, populate the new field with today's date or another date and set the time to 7:00 pm.
- Run the following code in the dev console.
Product2 prod = [SELECT id, ExpirationDate__c FROM product2 WHERE ExpirationDate__c != null limit 1];
Date dd = prod.ExpirationDate__c.date();
System.debug(LoggingLevel.ERROR, prod.ExpirationDate__c);
System.debug(LoggingLevel.ERROR, dd);
- In the debug log, note the date difference after converting the datetime value to date value in the log.
Please disregard what's written below:
Can anyone explain why I'm getting a date in the past when trying to convert today's date in datetime format to date format?
Datetime d = system.today();
System.debug(LoggingLevel.ERROR, JSON.serialize(d));
Date d2 = d.date();
System.debug(LoggingLevel.ERROR, JSON.serialize(d2));
Date d3 = Date.newinstance(d2.year(), d2.month(), d2.day());
System.debug(LoggingLevel.ERROR, JSON.serialize(d3));
String dstr = JSON.serialize(d3).substring(1, 11);
System.debug(LoggingLevel.ERROR, dstr);
Date d4 = (Date)JSON.deserializeStrict(dstr, Date.class);
System.debug(LoggingLevel.ERROR, JSON.serialize(d4));