function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
UndertowUndertow 

Date format in SOQL query?

Is it possible to format date or date/time in SOQL query, like in SQL query?

 

SQL example: DATE_FORMAT(date, '%d.%m.%y %H:%i ')

 

 

 

 

 

SurekaSureka

Hi,

 

Yes. You can. If date is the field name, then try date.format();. Also you can specify the required format as a string to the format method.

 

Thanks

UndertowUndertow

Hi Sureka, and thank you for your reply.

 

However, I tried this:  [SELECT id, date__c.format('YYYY-MM-DD'), Heading__c, Content__c FROM News__c LIMIT 3 ]; 

 

...but an error message  unexpected token: 'YYYY-MM-DD' was displayed.

 

What went wrong?

SurekaSureka

Hi,

 

The below sample code will give you in the required format ie.yyyy-mm-dd

 

Date todaydate = Date.Today();
String formatdate = String.valueOf(todayDate);
system.debug(formatdate);

 

Thanks

JimRaeJimRae

You can't do it directly in the SOQL query.  SOQL is a limited subset of standard SQL functionality.

What has already been suggested here is that you could accomplish your goal using Apex code.

Depending on what you are trying to do specifically, there are a variety of ways to accomplish this.

If you are trying to create a list of items that would all be displayed, I would suggest you consider a custom wrapper class.

 

Something like this:

 

 

List<cNews> newslist = new List<cNews>();
public class cNews{
public ID nid {get; set;}
public String nDate {get; set;}
public String nHeading {get; set;}
public String nContent {get; set;}
public cNews(News__c n){
    this.nid=n.id;
    this.nDate=n.date__c.format('yyyy-MM-dd');
    this.nHeading=n.Heading__c;
    this.nContent=n.Content__c;
}
}
for(News__c n: [SELECT id, date__c, Heading__c, Content__c FROM News__c LIMIT 3 ]){
     newslist.add(new cNews(n));
} 

 

 

 

$fdcuser$fdcuser

I keep getting the following error message when I attempt to format the date with a mask

"Method does not exist or incorrect signature: [Date].format(String)"

 

It fails at this line - this.nDate=n.date__c.format('yyyy-MM-dd')