Reputation: 564
I have a date variable (dd/mm/yyyy
).
I need to create a similar variable that is equivalent to Dec. 31 2016 to use it in a calculation.
How would I do this?
Upvotes: 0
Views: 274
Reputation: 37208
I take it that you have a numeric daily date variable. Some people hold dates as strings, which isn't very useful in Stata, and there are other kinds of numeric date variable.
A date like 31 December 2016 is a constant which can be calculated as
. di mdy(12, 31, 2016)
20819
and for display could be
. di %td mdy(12, 31, 2016)
31dec2016
You can get the same result in other ways, such as
. di daily("31 Dec 2016", "DMY")
20819
Nothing stops you putting this constant in a variable, but that just copies the same value as many times as you have observations, and is for most purposes pointless. Either use it directly or make your code easier to understand by using some evocative macro or scalar name:
. local Dec_31_2016 = mdy(12, 31, 2016)
. local today = mdy(8, 7, 2018)
. di `today' - `Dec_31_2016'
584
I have guessed that the most likely use for a date constant is to calculate time elapsed since some benchmark date.
Upvotes: 0
Reputation:
You need to use the daily()
function and then format
the numeric variable accordingly:
clear
set obs 1
generate date = daily("31Dec2016", "DMY")
format %tdMonDDCCYY date
list
+-----------+
| date |
|-----------|
1. | Dec312016 |
+-----------+
Type help daily()
and help format
from Stata's command prompt for details.
Upvotes: 1