Home  /  Resources & support  /  FAQs  /  Handling date information when numbers are in a continuous sequence

How do I convert date variables into Stata elapsed dates when the numbers run together, like 4151999?

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