DateTime.TryParse century control C#

前端 未结 5 1487
轻奢々
轻奢々 2020-11-28 15:57

The result of the following snippet is \"12/06/1930 12:00:00\". How do I control the implied century so that \"12 Jun 30\" becomes 2030 instead?

    string          


        
5条回答
  •  温柔的废话
    2020-11-28 16:08

    I'd write a re-usable function:

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

    Here's my list of quasi-date strings

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

    Scan over it like so:

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

    Notice that it handles 30 as 2030 now instead of 1930...

提交回复
热议问题