How to format date to Yyyyy-MM-Dd through Apex?

230    Asked by DianaCampbell in Devops , Asked on Jul 25, 2023

I am creating dynamic SOQL query for the search page with the below-mentioned code: VFP

Apex:
My Invoice_Date__c is a date field in the object
If I execute the following code in Anonymous window I do see the correct format but with my building dynamic SOQL I see the 2017-07-17 00:00:00
Date d = s.Invoice_Date__c; string dateStr = DateTime.newInstance(d.year(),d.month(),d.day()).format('yyyy-MM-dd'); system.debug('//' + dateStr);
Dynamic query building:
if (s.Invoice_Date__c != null) { Datetime d = s.Invoice_Date__c; String dateOutput

Despite selecting today’s date , in debug its displaying another date. How to format date to Yyyyy-MM-Dd through Apex?

Answered by Diane Carr

The same thing is not performed for both examples. In the very first example, foo is used but in the second case bar is used. What is performed in bar is known as Type Coercion where a date is assigned to a Datetime. That offers it a Time instance of (0,0,0,0). And a Time Zone of GMT. You can fix bar by utilizing formatGmt.

String qux(Date input) { // your second example rewritten Datetime output = input; return output.formatGmt('yyyy-MM-dd'); // ^^^ }
You could also think about your original bar as being equivalent to a slight change in baz:
String quux(Date input) { Datetime output = Datetime.newInstanceGmt(input, Time.newInstance(0,0,0,0)); // now output is the same as it was in `bar` return output.format('yyyy-MM-dd'); }
You have the Datetime in the GMT Timezone, so you need to use formatGmt:
String garply(Date input) { Datetime output = Datetime.newInstanceGmt(input, Time.newInstance(0,0,0,0)); // now output is the same as it was in `bar` return output.formatGmt('yyyy-MM-dd'); // ^^^ }
Salesforce date format followed by the field refers to YYYY/MM/DD, and the next variations that has a time stamp also like YYYY-MM-DD hh:mm:ss.

DevOps certification training provided at JanBask offers an extensive training on the core concepts of devOps from the comfort of your place without the need to travel to the physical location. The company provides training through exciting e-tools that makes the learning fun and simple.



Your Answer

Interviews

Parent Categories