Hello all,

Using Stata 15.1/IC

I've been using a do file for the past 8 months or so that automatically creates folders using the mkdircommand with system dates. I run the file once a month. The data are from a database as of the prior month end, so I desire to create a folder directory structure that would correspond to the year of the prior month and a subfolder with the name of the prior month. The code I've been using is:

Code:
**Create project directory for last month's data files
local path "C:/Users/Project" //Project Directory
local lastmonth = word(c(Months), (month(td(`c(current_date)')))-1) //Name of the month prior to this month--does not work in January
local year = (year(td(`c(current_date)'))) //Current year

cd "`path'"
capture mkdir "`year'/`lastmonth'"
For example, if I run this in November 2018, this would create the directory "C:/Users/Project/2018/October" and the rest of my do file ends up exporting files to this folder.

This works in all months of the year except for January. This is because the local for the name of the prior month (local lastmonth above) stores the name of the month that corresponds to the nth-1 word of the system generated c(Months) list. Because it's now January, it's storing nothing because there is no 0th month of the year. And the local year macro is simply the current year, so this wouldn't be correct in 2019 (since I would want the year of the prior month, in this case 2018).

The adjustments to the macros are probably not too hard to change to get it to return what I need for January 2019 (i.e. "C:/User/Project/2018/December"). Lesson learned: I should have realized that because something worked several times, it's not guaranteed to work in all cases.

I'd really appreciate some guidance on what commands (or approaches) would work year round, where no adjustments would need to be made to the do file for any of the months. Thanks!