Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Devops
  3. Question
Devops

How to format date to 'yyyy-MM-dd' using Apex

Asked by Anisha Dalal May 27, 2024 10.0K views 3 answers
Share

About this question

 I'm building dynamic SOQL query for the search page I have the following 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 = d.format('yyyy-MM-dd'); string invoiceDateFormated = DateTime.newInstance(d.year(),d.month(),d.day()+1).format('yyyy-MM-dd'); system.debug('dateOutput: ' + dateOutput); query += ' and Invoice_Date__c = '+invoiceDateFormated ; }

other thing I have noticed that even if I select today's date which is 07/17/2017 but in debug it showing me 07/16/2017 that's why I end-up adding +1 What is salaes force dateformat?

Your answer

3 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Feb 3, 2025

In Apex, you can format a date to the yyyy-MM-dd format using the format() or formatGMT() methods, or by manually constructing the date string. Here are different ways to achieve this:

1. Using format() Method

If the user's locale settings match the desired format, format() can be used:

Date myDate = Date.today();
String formattedDate = myDate.format(); // Formats based on user locale
System.debug(formattedDate);

However, this method depends on the user's locale, so it might not always return yyyy-MM-dd.

2. Using formatGMT() for a Fixed Format

To ensure consistency across all users:

Date myDate = Date.today();
String formattedDate = myDate.formatGMT('yyyy-MM-dd');
System.debug(formattedDate);

This is useful if you need a fixed format without relying on locale settings.

3. Manually Formatting the Date

You can also construct the string manually:

Date myDate = Date.today();
String formattedDate = myDate.year() + '-' + 
                       String.valueOf(myDate.month()).padLeft(2, '0') + '-' + 
                       String.valueOf(myDate.day()).padLeft(2, '0');
System.debug(formattedDate);

This approach ensures an exact yyyy-MM-dd format regardless of settings.

Best Practice

  • Use formatGMT('yyyy-MM-dd') for a reliable and locale-independent format.
  • If handling time zones, consider DateTime instead of Date and use formatGMT().

Would you like further customization based on your use case?

Was this helpful?

More Devops discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest DevOps Blogs

Guides, tips and career advice on DevOps from JanBask experts.