*! version 2.0.1 10october2023

datefrac -- Turn dates into fractional years

Syntax

datefrac datevar , generate(newvar) [order(dateorder)]

datefrac_options

generate(newvar) generate numeric newvar corresponding to string or numeric datevar

order(dateorder) identify the day/month/year order of string datevar, such as DMY or MDY

datevar is an existing variable in either string or Stata date format representing an exact calendar date.

dateorder is the s2 block that denotes the day, month, and year ordering/format of datevar in accordance with f_date.

Description

datefrac takes any variable that represents an exact date and generates a numeric variable representing the fraction of that year that has passed at the beginning of that date by taking the number of days since 1 January of a given year, dividing that number by 365, and adding the resulting fraction to the given year. For example, datefrac assigns the value 2020.000 (2020 + 0/365) to the date 1 January 2020 and the value 1999.17260 (1999 + 63/365) to the date 4 March 1999. It also accounts for leap years if the year is a multiple of 4, assigning the value 2000.17486 (2000 + 64/366) to the date 4 March 2000.

The command is not designed for variables such as monthly dates (March 1999) that do not have information on day of year, but it will run on date-time variables that can provide information on day, month, and year.

Options

generate(newvar) is required. It specifies the name of the numeric variable that datefrac creates.

order(dateorder) is required if datevar is still a string variable that has not been converted to Stata date format. It is directly equivalent to s2 in the help file for f_date. If datevar is a variable that has already been converted to Stata date format, this option is not required.

Example

If I had a string variable called "birthdate" with observations in the format "04 March 1999" and wanted to create a numeric variable called "birthdatefrac", I would use the following command:

. datefrac birthdate, gen(birthdatefrac) order(DMY)

but if instead the variable "birthdate" was already in Stata date format, I could omit the order() option:

. datefrac birthdate, gen(birthdatefrac)

and get the same result.

Remarks

If you have any suggestions for improving this command or would like to collaborate on some similar project, email me at labhours@tmorg.org and we'll get in contact!