Ordinal dates in Stata – ith day and week of month

 

clear

// seed some days
set obs 2300
gen daily = mdy(12,31,2019) + _n
format daily %td

// the basics
gen yr = year(daily)
gen mo = month(daily)
label define mo ///
    1 "Jan" 2 "Feb" 3 "Mar" 4 "Apr" 5 "May" 6 "Jun" ///
    7 "Jul" 8 "Aug" 9 "Sep" 10 "Oct" 11 "Nov" 12 "Dec"
label values mo mo

gen day_wk = dow(daily) + 1
label define day_wk ///
   1 "Sun" 2 "Mon" 3 "Tues" 4 "Wed" 5 " Thu" 6 "Fri" 7 "Sat"
label val day_wk day_wk

// ith week of the year
bysort yr : gen wk_yr = sum(dow(daily) == 1) + 1

// ith day of the year
bysort yr : gen day_yr = _n

// ith day of the month
bysort yr mo : gen day_mo = _n

// ith week of the month
bysort yr mo : gen wk_mo = int(day_mo / 7) + 1

// making the first of something is easy
gen firstmonday = wk_mo==1 & day_wk==1
gen firstmondaymarch = firstmonday & mo==3

// but what about the last?
gen negdaymo = -day_mo
sort yr mo negdaymo
bysort yr mo : gen lastweek = _n<=7
sort yr mo day_mo
drop negdaymo

list in 1/70

gen lastfriday = day_wk==5 & lastweek

 

Leave a Reply

Your email address will not be published. Required fields are marked *