DateTime.TryParse century control C#

前端 未结 5 1460
轻奢々
轻奢々 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:24

    It's tricky, because the way two digit years work with TryParse is based on the TwoDigitYearMax property of the Calendar property of the CultureInfo object that you are using. (CultureInfo->Calendar->TwoDigitYearMax)

    In order to make two digit years have 20 prepended, you'll need to manually create a CultureInfo object which has a Calendar object with 2099 set as the TwoDigitYearMax property. Unfortunately, this means that any two digit date parsed will have 20 prepended (including 98, 99 etc.) which is probably not what you want.

    I suspect that your best option is to use a 3rd party date parsing library instead of the standard tryparse that will use the +50/-50 year rule for 2 digit years. (that a 2 digit year should be translated into a range between 50 years before this year and 50 years greater than this year).

    Alternatively, you could override the ToFourDigitYear method on the calendar object (it's virtual) and use that to implement the -50/+50 rule.

提交回复
热议问题