2010-09-08 137 views
2

我遇到了一個datetime相關的問題,我的程序需要改變用戶輸入的日期字符串是否有效。C#DateTime.TryParse日期年份值交換。 2月30日02

該程序旨在處理日期值範圍從01/01/2000〜31/12/2020和字符串格式是「2 2月10日」。

我面臨的問題是,有時用戶輸入像「30 2月10日」這樣的值(這個值是無效的),它通過格式檢查,但DateTime.TryParse會交織這個字符串爲「10/02/1930 12:00 00:00」。

我對此問題的解決方案是從字符串中提取日期,月份,年份值,並嘗試重構日期字符串。請參閱下面的代碼。

private static void IsValidDateValue(string userInputValue, CustomValidatorExtended custValidator, string errorMessage, ref bool isValid) 
    { 
     Regex regexValue = new Regex(SHORT_DATE_VALUE); 
     if (regexValue.IsMatch(userInputValue)) 
     { 
      Match match = regexValue.Match(userInputValue); 
      int dayValue; 
      if (!Int32.TryParse(match.Groups["date"].Value, out dayValue)) 
      { 
       custValidator.ErrorMessage = errorMessage; 
       isValid = false; 
       return; 
      } 
      int monthValue; 
      if (!Int32.TryParse(ConvertMonthNameToNumber(match.Groups["month"].Value).ToString(), out monthValue)) 
      { 
       custValidator.ErrorMessage = errorMessage; 
       isValid = false; 
       return; 
      } 
      //this application is designed to handle only from year 2000 ~ 2020 and user only suppose to enter 2 digits for year 
      int yearValue; 
      if (!Int32.TryParse("20" + match.Groups["year"].Value, out yearValue)) 
      { 
       custValidator.ErrorMessage = errorMessage; 
       isValid = false; 
       return; 
      } 
      DateTime dtParse; 
      if (!DateTime.TryParse(yearValue + "-" + monthValue + "-" + dayValue, out dtParse)) 
      { 
       custValidator.ErrorMessage = errorMessage; 
       isValid = false; 
       return; 
      } 
     } 
     else 
     { 
      isValid = true; 
      return; 
     } 
    } 

有沒有更簡單的方法使用.net框架默認方法來解決這個日期年值交換問題?

感謝&問候,

回答

1
DateTime dt = default(DateTime); 
string val = "31 Feb 09"; 
bool valid = DateTime.TryParseExact(val, "d MMM yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt); 

valid爲false,和葉dt不變。當val設置爲"31 Mar 09"時,它將設置爲true,dt包含2009-03-31T00:00:00且未指定時區。如果需要,請使用不同的DateTimeStyles值指定本地或UTC。

+0

您不需要'default(DateTime)'部分,因爲當將變量作爲'out'傳遞時,該值將被分配。 – 2010-09-08 00:49:15

+0

不,你不知道。這是一種風格的東西。 – 2010-09-08 01:17:46

1

這是你想要什麼:

DateTime parse = DateTime.ParseExact(parseString, "dd MMM yy", CultureInfo.CurrentCulture); 

或檢查其能否正常工作:

DateTime parse; 
DateTime.TryParseExact(parseString, "dd MMM yy" CultureInfo.CurrentCulture, out parse); 
+0

非常感謝Richard ...... – jeffreychi 2010-09-08 01:32:13

相關問題