DateTime.TryParse世纪控件C#

以下代码段的结果是“12/06/1930 12:00:00”。 如何控制隐含的世纪,以便“12月30日”变为2030?

string dateString = "12 Jun 30"; //from user input DateTime result; DateTime.TryParse(dateString, new System.Globalization.CultureInfo("en-GB"),System.Globalization.DateTimeStyles.None,out result); Console.WriteLine(result.ToString()); 

请暂时搁置这样一个事实,即正确的解决方案是首先正确指定日期。

注意:结果与运行代码的pc的系统日期时间无关。

答:谢谢Deeksy

  for (int i = 0; i <= 9; i++) { string dateString = "12 Jun " + ((int)i * 10).ToString(); Console.WriteLine("Parsing " + dateString); DateTime result; System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-GB"); cultureInfo.Calendar.TwoDigitYearMax = 2099; DateTime.TryParse(dateString, cultureInfo , System.Globalization.DateTimeStyles.None, out result); Console.WriteLine(result.ToString()); } 

这很棘手,因为使用TryParse的两位数年份的方式基于您正在使用的CultureInfo对象的Calendar属性的TwoDigitYearMax属性。 (CultureInfo->日历 – > TwoDigitYearMax)

为了使两位数年份前置20个,您需要手动创建一个CultureInfo对象,该对象具有一个设置为2099的Calendar对象作为TwoDigitYearMax属性。 不幸的是,这意味着解析的任何两位数日期将有20个前置(包括98,99等),这可能不是你想要的。

我怀疑你最好的选择是使用第三方日期解析库而不是标准的tryparse,它将使用+ 50 / – 50年规则2位数。 (2位数年份应转换为今年前50年至今年50年之间的范围)。

或者,您可以覆盖日历对象上的ToFourDigitYear方法(它是虚拟的)并使用它来实现-50 / + 50规则。

我写了一个可重用的函数:

 public static object ConvertCustomDate(string input) { //Create a new culture based on our current one but override the two //digit year max. CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.LCID); ci.Calendar.TwoDigitYearMax = 2099; //Parse the date using our custom culture. DateTime dt = DateTime.ParseExact(input, "MMM-yy", ci); return new { Month=dt.ToString("MMMM"), Year=dt.ToString("yyyy") }; } 

这是我的准日期字符串列表

 List dates = new List(new []{ "May-10", "Jun-30", "Jul-10", "Apr-08", "Mar-07" }); 

像这样扫描它:

 foreach(object obj in dates.Select(d => ConvertCustomDate(d))) { Console.WriteLine(obj); } 

请注意,它现在处理30作为2030而不是1930 …

您正在寻找Calendar.TwoDigitYearMax属性 。

Jon Skeet已经发布了一些内容,你可能会发现它很有用。

我有一个类似的问题,我用正则表达式解决了它。 在你的情况下,它看起来像这样:

 private static readonly Regex DateRegex = new Regex( @"^[0-9][0-9] (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9][0-9]$", RegexOptions.Compiled | RegexOptions.ExplicitCapture); private static string Beautify(string date) { var match = DateRegex.Match(date); if (match.Success) { // Maybe further checks for correct day return date.Insert("dd-MMM-".Length, "20"); } return date; } 
 result = year.ToString().Length == 1 || year.ToString().Length == 2 ? "1" : (Convert.ToInt32(year.ToString() .Substring(0, (year.ToString().Length - 2))) + 1).ToString();