下面是我的舊代碼,效果很好,如果輸入的是這樣的「2017年1月1日」拆分輸入和在不同的變量存儲C#
string monthfrom;
string yearfrom;
string valfrom = "01/01/2017";
valfrom = valfrom.Replace("/", string.Empty);
monthfrom = valfrom.Substring(0, 2);
yearfrom = valfrom.Substring(valfrom.Length - 4);
pdfFormFields.SetField("Month[0]", monthfrom);
pdfFormFields.SetField("Year[0]", yearfrom);
結果:月[0] = 01年[0] = 2017
但如果輸入是這樣的2017年1月1日的結果會是這樣
月[0] = 11年度[0] = 2017
我知道錯誤的原因是因爲this monthfrom = valfrom.Substring(0,2); ,所以我改變了代碼是這樣的。
char[] delimiterChars = { '/' };
string text = "1/1/2017";
string[] words = text.Split(delimiterChars);
string result = string.Empty;
foreach (string s in words)
{
result += s;
}//foreach
不過我這裏有一個問題,我想投入到在不同的變量,但我不知道如何做到這一點也沒有一個單一的想法。
下面是我出來就把目標,如果輸入是2017年1月1日& 2017年1月1日
輸入:2017年1月1日
月= 1天= 1年= 2017年
輸入:2017年1月1日
月= 01天= 01年= 2017年
爲什麼不將值從1/1/2017更改爲dateValue.ToString(「MM/dd/yyyy」);首先得到01/01/2017?這是爲您的第一個代碼提供的解決方案 – jace
您不應該手動執行此類內容,而應使用DateTime類上提供的方法進行解析。 – loneshark99
哦,如果它不是日期時間,它的值只是一個字符串輸入,轉換字符串不是一個選項。我剛剛給它的日期時間 – jace