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
Elizabeth BryantElizabeth Bryant 

Datetime format returning wrong value after first iteration

I am parsing an application into XML format and the expected return value for dates is DD-MMM-YY. The fields in question are parsed inside of a for loop. The first iteration returns the correct format for DOB, but the second iteration returns wrong. I'm hoping that someone can help me pinpoint what the issue is here.

Thanks in advance! 

Apex Code: 
for(Integer i=0; i< memToXML.size();i++){
      w.writeStartElement(null,'DOB','');
      String dt =   DateTime.newInstance(memToXML[i].DOB__c.year(),memToXML[i].DOB__c.month(),memToXML[i].DOB__c.day()).format('DD-MMM-YY');
      system.debug('>>> Converted DOB: ' + dt);
      w.writeCharacters(dt);
      w.writeEndElement();

XML output:
Member One:  <soapenv:DOB>02-Jan-80</soapenv:DOB> ***Original 1/2/1980***
Member Two:  <soapenv:DOB>196-Jul-99</soapenv:DOB> ***Original 7/15/1999***

 
Best Answer chosen by Elizabeth Bryant
Glyn Anderson 3Glyn Anderson 3
Elizabeth,

The problem is the case of your date format string - it is important.  "DD" returns the number of the day in the year, while "dd" returns the number of the day in the month.  So, 1/2/1980 worked fine, because it was both the second day of the month and the second day of the year; while 7/15 is the 196th day of the year.  Change your format string to "dd-MMM-yy".  I have changed the year to lowercase as well, as "YY" has a subtly different meaning.  Keep the month uppercase.  "mm" yields the minute within the hour - not the month.

For more info on SimpleDateFormat strings, see: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

All Answers

Glyn Anderson 3Glyn Anderson 3
Elizabeth,

The problem is the case of your date format string - it is important.  "DD" returns the number of the day in the year, while "dd" returns the number of the day in the month.  So, 1/2/1980 worked fine, because it was both the second day of the month and the second day of the year; while 7/15 is the 196th day of the year.  Change your format string to "dd-MMM-yy".  I have changed the year to lowercase as well, as "YY" has a subtly different meaning.  Keep the month uppercase.  "mm" yields the minute within the hour - not the month.

For more info on SimpleDateFormat strings, see: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
This was selected as the best answer
Elizabeth BryantElizabeth Bryant
I actually just figured this out on my own and was about to update my question with the answer. I didn't realize that the dates I used in my previous test were all January dates either so I didn't realize I had a syntax issue and had a slight freakout. 

Thanks for taking the time to help!