需要使用TryParse将dd.MM.yyyy解析为DateTime

我需要将字符串解析为DateTime。 该字符串始终采用以下格式

“10.10.2010”这意味着dd.MM.yyyy,用点分隔。

我想使用DateTime.TryParse或任何其他方法。 请建议。

UPDATE

更新了问题。 我只是在寻找实现目标的正确方法。 不是手动解析

TryParse不允许您指定格式 – 但您可以使用TryParseExact

 DateTime date; if (DateTime.TryParseExact(text, "dd'.'MM'.'yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { // Success } else { // Parse failed } 

请注意,点不一定要使用引号进行转义,但我个人喜欢将任何文字文本放在引号中,以确保它不会被更改。 这是个人偏好的事情 – 如果你愿意,你当然可以使用“dd.MM.yyyy”。

同样地,我已经指定了不变文化,这是我通常为固定的自定义风格做的 – 但如果你愿意,你可以使它使用当前的文化或特定的其他文化。 当你使用自定义样式(而不是像“长日期”这样的标准样式)时,不太可能产生任何差异。

使用TryParseExact方法:

 DateTime parsed; if (DateTime.TryParseExact(yourString, "dd'.'MM'.'yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out parsed)) { // success } 

为什么不使用ParseExact呢?

 var theDate = DateTime.ParseExact("dd.MM.yyyy", yourDateString, CultureInfo.InvariantCulture); 

巴西编解码器

 public static bool IsDateTime(string txtDate) { DateTime tempDate; return DateTime.TryParseExact(txtDate,"dd/MM/yyyy", new CultureInfo("pt-BR"), DateTimeStyles.None, out tempDate); } 

使用DateTime.TryParseExact(…)

您可以使用DateTime.TryParseExact

尝试“ddMMyyy”,不要“ – /”。

我发现jquery datepicker会在字符串中添加不可打印的字符。 因此,当您尝试转换为其他格式时,每次都会抛出无效的日期错误。 就我而言,我只是试图将它转换回用户当时所处文化的时间戳。 这是一种有点hacky的方法,但它对我有用。

  static public string ToDigitsOnly(string input) { Regex digitsOnly = new Regex(@"[^\d]"); return digitsOnly.Replace(input, ""); } static private DateTime ConvertDateTimeToDate(string dateTimeString, String langCulture) { System.DateTime result; string[] dateString = dateTimeString.Split('/'); try { if (langCulture != "en") { int Year = Convert.ToInt32(ToDigitsOnly(dateString[2])); int Month = Convert.ToInt32(ToDigitsOnly(dateString[1])); int Day = Convert.ToInt32(ToDigitsOnly(dateString[0])); result = new DateTime(Year, Month, Day, 00, 00, 00); } else { int Year = Convert.ToInt32(dateString[2]); int Month = Convert.ToInt32(dateString[0]); int Day = Convert.ToInt32(dateString[1]); result = new DateTime(Year, Month, Day, 00, 00, 00); } } catch { // last attempt result = Convert.ToDateTime(dateTimeString, CultureInfo.GetCultureInfo("en-US")); } return result; }