Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: 3 methods for converting a string date to Stata format


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: 3 methods for converting a string date to Stata format
Date   Fri, 5 Jan 2007 19:17:46 -0000

This kind of thread summary is very helpful. 

What what Michael calls Method 3, a -format()- option
to -todate- from SSV allows his code to be cut by one line. 
Also, I don't quite understand why he recommends using -destring- 
first: the help for -todate- does explain that 
it can process string variables directly. You might
need -destring- if there were extraneous characters that
needed to be removed. 

Nick 
[email protected] 

Michael McCulloch
 
> I recently posted a question on how to separate a string date 
> into Stata 
> date. I would like to share the three methods which I've learned:
> 
> * 3 methods for converting a string date to Stata format
> clear
> input datedx
>      19900417
>      19880107
>      19930407
>      19880819
>      19890127
> end
> 
> * METHOD 1
> tostring datedx, replace
> generate str4 dxyr1= substr(datedx,1,4)
> generate str2 dxmo1 = substr(datedx,5,6)
> generate str2 dxda1 = substr(datedx,7,8)
> destring dx*, replace
> gen datedx1 = mdy(dxmo1, dxda1, dxyr1)
> format datedx1 %d
> 
> * METHOD 2 (by Maarten Buis)
> destring datedx, replace
> gen int dxyr2 = floor(datedx/10000)
> gen int dxmo2 = floor((datedx-dxyr2*10000)/100)
> gen int dxda2 = datedx - dxyr2*10000 - dxmo2*100
> gen datedx2 = mdy(dxmo2, dxda2, dxyr2)
> format datedx2 %d
> 
> * METHOD 3 (by Nick Cox; first must run .ssc install todate)
> * uses the dates as numbers (i.e. use -destring- first) then 
> the floor 
> function.
> todate datedx, gen(datedx3) pattern(yyyymmdd)
> format datedx3 %d
> list datedx datedx1 datedx2 datedx3 in 1/5

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index