I am working on a project where occasionally I need to keep time using dates in the format YYYYMMDD. I sometimes also need to move back and forth between these dates and numeric year, month, day, which requires things like turning the numeric month 1 into the string "01".

The general syntax for turning numbers to strings with leading zeroes is easy enough. Here's an example with social security numbers:

gen str9 ssn_string=string(ssn_numeric, "%09.0f")

For dates, this syntax would translate like so:

 local when c(current_date)' display "when'"  local pieces "year month day" local length "4 2 2" forvalues i=1/3 { local w: word i' of pieces' local k: word i' of length' local w'=string(w'(date("when'","DMY")),"%0k'.0f") } local when="year'month'day'" display "when'" 

Of course, you don't need to use the string type. Getting back to Stata's original social security number example, if you want leading zeroes but you also want to keep the numeric type, you can simply say

format ssn %09.0f

See the Stata help for format.