2017-04-27 58 views
0

下面是我的舊代碼,效果很好,如果輸入的是這樣的「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年

+0

爲什麼不將值從1/1/2017更改爲dateValue.ToString(「MM/dd/yyyy」);首先得到01/01/2017?這是爲您的第一個代碼提供的解決方案 – jace

+0

您不應該手動執行此類內容,而應使用DateTime類上提供的方法進行解析。 – loneshark99

+0

哦,如果它不是日期時間,它的值只是一個字符串輸入,轉換字符串不是一個選項。我剛剛給它的日期時間 – jace

回答

1
string x = "1/1/2017"; 
string y = "01/01/2017"; 
DateTime dateTime; 
if (DateTime.TryParse(y, out dateTime)) 
{ 
    Console.WriteLine($"Day = {dateTime.Day}"); 
    Console.WriteLine($"Month = {dateTime.Month}"); 
    Console.WriteLine($"Year = {dateTime.Year}"); 
} 
else 
{ 
    Console.WriteLine("Date cannot be parsed"); 
} 
0

解析日期時間,然後獲取相關字段。在這種情況下,你不必擔心字符串的格式。

public class ParsedDate 
     { 
      public int day { get; set; } 
      public int month { get; set; } 
      public int year { get; set; } 
     } 


     public ParsedDate ParseDate(string inputString) 
     { 
      DateTime outDate; 

      ParsedDate returnObject = new ParsedDate(); 

      if (String.IsNullOrEmpty(inputString)) 
      { 
       throw new ArgumentException("String can not be empty"); 
      } 

      DateTime.TryParse(inputString, out outDate); 

      if (outDate != null) 
      { 
       returnObject = new ParsedDate 
       { 
        day = outDate.Day, 
        month = outDate.Month, 
        year = outDate.Year 
       }; 
      } 

      return returnObject; 
     }