|Title||Handling date information when numbers are in a continuous sequence|
|Author||David Reichel, StataCorp|
The date() function can convert virtually any date format into elapsed dates, which is the format Stata uses to manipulate date information. Elapsed dates are calculated as the number of days from January 1, 1960. This format is useful for adding or subtracting dates and changing the format of date variables.
Converting dates is easy to do. The date() function can handle a date that is a continuous number. For example, suppose you had the numeric variable datevar:
. list +----------+ | datevar | |----------| 1. | 12031999 | 2. | 2081998 | 3. | 4071997 | +----------+
To convert the above date variable to an elapsed date format, you must first convert the numeric variable to a string and then use the date() function. For example,
. tostring datevar, replace format(%20.0f) datevar was long now str8 . replace datevar = "0" + datevar if length(datevar) == 7 (2 real changes made) . list +----------+ | datevar | |----------| 1. | 12031999 | 2. | 02081998 | 3. | 04071997 | +----------+ . gen edatevar = date(datevar,"MDY") . format edatevar %td . list +----------------------+ | datevar edatevar | |----------------------| 1. | 12031999 03dec1999 | 2. | 02081998 08feb1998 | 3. | 04071997 07apr1997 | +----------------------+
Another solution is to use the todate command written by Nicholas J. Cox. To obtain todate, type
. ssc install todate
Classroom and web training
Teaching with Stata
Statalist: The Stata Forum
Last updated: 16 November 2022
StataCorp LLC (StataCorp) strives to provide our users with exceptional products and services. To do so, we must collect personal information from you. This information is necessary to conduct business with our existing and potential customers. We collect and use this information only where we may legally do so. This policy explains what personal information we collect, how we use it, and what rights you have to that information.
These cookies are essential for our website to function and do not store any personally identifiable information. These cookies cannot be disabled.
Please note: Clearing your browser cookies at any time will undo preferences saved here. The option selected here will apply only to the device you are currently using.