DateTime.TryParse世纪控件C#

时间:2009-11-19 02:35:42

标签: c# datetime tryparse

以下代码段的结果是“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());

请暂时搁置正确的解决方案首先正确指定日期的事实。

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

答案:谢谢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());
    }

5 个答案:

答案 0 :(得分:21)

这很棘手,因为两个数字年使用TryParse的方式基于您正在使用的CultureInfo对象的Calendar属性的TwoDigitYearMax属性。 (CultureInfo-&GT; [日历&GT; TwoDigitYearMax)

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

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

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

答案 1 :(得分:11)

我写了一个可重复使用的功能:

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<string> dates = new List<string>(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 ......

答案 2 :(得分:2)

您正在寻找Calendar.TwoDigitYearMax Property

Jon Skeet has posted对此你可能会觉得有用。

答案 3 :(得分:1)

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

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;
}

答案 4 :(得分:-1)

result = year.ToString().Length == 1 
      || year.ToString().Length == 2 ? "1" 
       : (Convert.ToInt32(year.ToString()
          .Substring(0, (year.ToString().Length - 2))) + 1).ToString();
相关问题