2016-06-07 2363 views
-2

我對Stata比較陌生。我有可變time一個字符串,記錄年份和月份的格式如下:Stata:將字符串轉換爲日期

2000m1 
2000m2 
2000m3 
... 
2015m12 

我想首先創建一個日期變量,看起來相同(但必須是在日期格式)以上。其次,我想將年份和月份分成兩個不同的變量,第三,我想將月份組件重命名爲1月,2月等。

對於第一個任務,命令date = date(time, "YM")返回一個空變量我無法弄清楚我做錯了什麼。

+0

這裏引用了什麼是一個命令不是一個完整的命令:大概是一個啓動'產生'的意圖。 –

+0

有人猜測,因爲downvoters沒有解釋,downvoting反映了明顯無法公正地閱讀文檔的判斷。 (SO不作爲初學者的論壇,但對於專業和發燒友程序員來說,閱讀文檔是最低要求。) –

回答

0

功能date()產量每天日期,不包月日期或任何其他類型的日期,是不是每天的日期。看到它的幫助(help date()),它開始

date(s1,s2[,Y]) 
     Description: the e_d date (days since 01jan1960) corresponding to s1 
        based on s2 and Y 

        s1 contains the date, recorded as a string, in virtually 
        any format. Months can be spelled out, abbreviated (to 
        three characters), or indicated as numbers; years can 
        include or exclude the century; blanks and punctuation are 
        allowed. 

        s2 is any permutation of M, D, and [##]Y, with their order 
        defining the order that month, day, and year occur in s1. 
        ##, if specified, indicates the default century for 
        two-digit years in s1. For instance, s2="MD19Y" would 
        translate s1="11/15/91" as 15nov1991. 

在本質上,它需要一天,一個月,一年,被告知。你提供了一個月和一年,而date()不會(不能)發揮。

正如在同一地方記錄的那樣,daily()是同一功能的同義詞,它是一種很好的習慣,可以用它來提醒自己(以及代碼的讀者)它的功能。

相應地,monthly()提供了一種更簡單的解決方案,可以根據字符串輸入創建月度日期,而不是您自己的答案。嘗試使用display(允許使用di)的解決方案,在您知道正確答案的簡單案例中。

. di monthly("2000m1", "YM") 
480 

. di %tm monthly("2000m1", "YM") 
2000m1 

閱讀文檔至關重要。請參閱help datetime開始。有很多解釋,日期有很多不同的形式,但都記錄在案。

另請參閱help datetime_display_formats瞭解如何以不同方式顯示日期。 (在這裏沒有「重命名」。)例如,

. di %tmMonth_CCYY monthly("2000m1", "YM") 
    January 2000 
0

試試這個代碼可以是你的作品

string Date1 = String.Format("{0}", Request.Form["date"]); 
     string Date2 = String.Format("{0}", Request.Form["date1"]); 

     Date1 = DateTime.Parse(Date1).ToString("yyyy-MM-dd"); 
     Date2 = DateTime.Parse(Date2).ToString("yyyy-MM-dd"); 
+0

謝謝,但「命令字符串無法識別」是我輸入第一條命令時得到的錯誤。 – firemind

+0

將此字符串替換爲字符串名稱 –

+1

這不是Stata語法。對於OP或任何其他人來說,它可能是也可能不是一個好的選擇,但解釋使用什麼語言是至關重要的。 –

1

我想通了第一部分。我張貼的答案,這裏任何人誰需要一個參考:

gen date = ym(real(substr(time, 1,4)),real(substr(time,6,2))) 

format date %tm 
+0

我在這裏逆轉了downvote。這在我看來並不是最好的答案(使用'monthly()'要簡單得多),但這是一個正確的答案。 –