Leading zeroes
Tuesday, 11 November 2008
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")),"%0`k'.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.
No. 1 — November 19th, 2008 at 3:29 pm
For the purpose of going from date in "m/d/yyyy" format to a string of "yyyymmdd" a faster way than your loop is:
string(date("1/1/2008","DMY"),"%tdCCYYDDNN")
No. 2 — December 4th, 2008 at 5:24 pm
[...] is a beautiful solution. Steli's comment in response to my post on leading zeroes had sent me riffling through the Stata manual (the Data Management volume has a section on dealing [...]