3
Datetime Createddate = system.now();
Datetime Duedate = Class.Method(Createddate,10);
//Converting to date format
Objinstance.Field__c= Date.newinstance( dueDate.month(), dueDate.day(),dueDate.year());
Date DueDateformatted = Duedate.Date();
//convert Date to string
String DateString = DueDateformatted.format();

My requirement is Created Date = In datetime Due Date = Date format in VF Page field But need to send String through integration .

Format() in Date Date class - Does it allow formatting in specific format like Datetime class ? I tried out but didn't work for me.

Ay suggestions?

1 Answer 1

7

If you want to specify a particular format (not just the default for your locale), leave it as Datetime. That type has a format method signature which accepts a String. You can supply any supported SimpleDateFormat:

String iso8601 = Datetime.now().format('yyyy-MM-dd');

You can save it as a Date in the database and then create a Datetime instance to format for your integration.

String iso8601 = Datetime.newInstance(myDateField, Time.newInstance(0,0,0,0)).format(...);

If you just care about formatting the output in Visualforce, you can use the <apex:outputText> tag as outlined in Visualforce Date formatting.

<apex:outputText value="{0, date, MMMM d','  yyyy}">
    <apex:param value="{!myRecord.SomeDateField__c}" /> 
</apex:outputText>
5
  • Thanks Adrian . But I also have a requirement to display the field as Date . In that case what would be the best practice? Creating two different fields ? Date and String ? Jan 21, 2017 at 3:29
  • @Vanilla_Sky See the updated answer. You can convert a Date instance to Datetime in order to get more flexibility in formatting. If you're going to store it, store it as a Date.
    – Adrian Larson
    Jan 21, 2017 at 23:33
  • @Vanilla_Sky Any remaining questions?
    – Adrian Larson
    Jan 26, 2017 at 23:10
  • My ideal flow of formatting would be like Datetime (returned as a value from a method call) -->Assign to a Date field of an object to display on VF Page --->Format YYYY-MM-DD and convert to string . I guess the second part will not be possible with Date type? Right now I am assigning Datetime formatted to YYYY-MM-DD to a string field additionally- But that's not a good practice I suppose. Jan 28, 2017 at 4:16
  • 1
    @Vanilla_Sky See updates for VF formatting. Store the actual Date or Datetime value. The database shouldn't be concerned with formatting.
    – Adrian Larson
    Jan 28, 2017 at 17:25

You must log in to answer this question.

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