+ Start a Discussion
avimeiravimeir 

Date in format YYYYMMDD

Hi,

 

How can I get a string representing today's date in the format YYYYMMDD ?

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
chris.noechris.noe

It won't fail, you just won't have a leading zero on single digit month or day values.  If  you want to have a leading zero on day or month, just check the length of the day and month strings returned.  If they are 1, just add a leading zero.  Something like the following:

 

Date dateToday = Date.today();
String sMonth = String.valueof(dateToday.month());
String sDay = String.valueof(dateToday.day());
if(sMonth.length()==1){
  sMonth = '0' + sMonth;
}
if(sDay.length()==1){
  sDay = '0' + sDay;
}
String sToday = String.valueof(dateToday.year()) + sMonth + sDay ;

 

All Answers

chris.noechris.noe

Try this:

 

Date dateToday = Date.today();
String sToday = String.valueof(dateToday.year()) + String.valueof(dateToday.month()) + String.valueof(dateToday.day());

 

avimeiravimeir

Thanks, but won't it fail in case the day or month are single-digit?

 

For example, 03-03-2012 will result in 201233  , right? I need it to be 20120303

chris.noechris.noe

It won't fail, you just won't have a leading zero on single digit month or day values.  If  you want to have a leading zero on day or month, just check the length of the day and month strings returned.  If they are 1, just add a leading zero.  Something like the following:

 

Date dateToday = Date.today();
String sMonth = String.valueof(dateToday.month());
String sDay = String.valueof(dateToday.day());
if(sMonth.length()==1){
  sMonth = '0' + sMonth;
}
if(sDay.length()==1){
  sDay = '0' + sDay;
}
String sToday = String.valueof(dateToday.year()) + sMonth + sDay ;

 

This was selected as the best answer
FlorSFFlorSF
string myDate = Datetime.now().format('yyyyMMdd');
Vikash AgarwalVikash Agarwal
I know it's very late but worth sharing for future ref : 
private String convertToDateFormat(Date d){ //YYYY-MM-DD
    if(d!= null){
        String month = String.valueOf(d.month()).leftPad(2,'0');
        String day =  String.valueOf(d.day()).leftPad(2,'0');
        return d.year() + '-' + month + '-' + day;
    }
    return null;
}