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
streetstreet 

Date format issue in apex class

I need date to be Formated to DD-MM-YYYY(02-03-2012)

 

But its coming as D-MM--YYYY(2-03-2012)

 

I need like this(02-03-2012)

 

Here is my code:

string DateString ;
string mon;
if(d1!=null)
{
integer red1 = d1.day();


integer red2 = d1.month();
if(red2==1){
mon = '01';

}
else if(red2==2){
mon = '02';
}
else if(red2==3){
mon = '03';


}
else if(red2==4){
mon = '04';
}
else if(red2==5){
mon = '05';
}
else if(red2==6){
mon = '06';


}
else if(red2==7){
mon = '07';
}
else if(red2==8){
mon = '08';
}
else if(red2==9){
mon = '09';


}
else if(red2==10){
mon = '10';
}
else if(red2==11){
mon = '11';
}
else if(red2==12){
mon = '12';


}
integer red3 = d1.year();
DateString = string.valueOf(red1)+'-'+mon+'-'+string.valueOf(red3);

}


Navatar_DbSupNavatar_DbSup

Hi,

Try the below code snippet as reference:

string currentdate=system.today().format();
system.debug('###########33'+currentdate);
list<string> date1=currentdate.split('/');
string finaldate=((integer.valueof(date1[1])<10)?'0'+date1[1]:date1[1])+'-'+((integer.valueof(date1[0])<10)?'0'+date1[0]:date1[0])+'-'+date1[2];
system.debug('^^^^^^^^^^^^^^^^^'+ finaldate);

 

OR

 

date dt=system.today();
string month=string.valueof(dt.month());
string day=string.valueof(dt.day());
if(integer.valueof(month) < 10)
month= '0' + month;
if(integer.valueof(day) < 10)
day= '0' + day;
date dNew=day +'-'+month+'-'+dt.year();
system.debug('@@@@@@@@@@@' + dNew);

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.

gaisergaiser
Date myDate = Date.newinstance(1960, 2, 17);

String pad2(Integer val) {
    if (val < 10) {
        return '0' + val;
    }
    return '' + val;
}
String dateFormatted = pad2(myDate.day()) + '-' + pad2(myDate.month()) + '-' + myDate.year();
System.debug('#date=' + dateFormatted);

 

Note 1 - the above code is not checking for null or negative value, as well as assumes that year is always 4 digits and does not need padding

 

Note 2 - the above code is for developer console, if you are using this in a class then you may want to declare "pad2" method as something like

private static pad2(Integer val) {

...

}