I'm new to Stata, and I'm wondering how can I change a string variable which contains a date to a date format. The data in the variable looks like this: yyyy-mm-dd Should I first remove the dashes so that Stata can recognize the format in order to later use gen var = date() ? Thank you for your help.
11.5k 10 10 gold badges 47 47 silver badges 72 72 bronze badges asked Aug 14, 2013 at 8:30 1,399 5 5 gold badges 20 20 silver badges 31 31 bronze badges did you get the answer you needed?\ Commented Aug 14, 2013 at 11:13The word "format" is treacherous here. "yyyy-mm-dd" as a pattern or style for holding dates is a format (sense 1). Assigning Stata's daily date display format with the format command is Stata's sense of the word (sense 2), but is not sufficient. Date format (sense 3) means daily dates being stored numerically and counted relative to 1 January 1960.
Commented Aug 14, 2013 at 12:07The Stata date function is smart about removing separator characters. See help datetime_translation under the section "the date function"
If your dates are in v1 and in the form yyyy-mm-dd you can specify the commands:
generate v2 = date(v1, "YMD") format %td v2
The YMD is called a mask, and it tells Stata the order in which the parts of the date are specified. The second line will assign the variable the Stata daily date format, which means that when you look at that variable in the data, it will be shown in human readable form. The date is stored, however, as the number of days since January 1, 1960.
The best way to experiment with the date function is to use the display command. The first line will display an integer representing the number of days since January 1, 1960. The second line will display the date in a human readable format.
display date("2013-08-14", "YMD") display %td date("2013-08-14", "YMD")