DateTime string parsing

前端 未结 3 1819
逝去的感伤
逝去的感伤 2020-12-16 19:58

I have made a generic parser for parsing ascii files. When I want to parse dates, I use ParseExact function in DateTime object to parse, but I get problems with the year.

3条回答
  •  爱一瞬间的悲伤
    2020-12-16 20:29

    Theoretically elegant way of doing this: change the TwoDigitYearMax property of the Calendar used by the DateTimeFormatInfo you're using to parse the text. For instance:

    CultureInfo current = CultureInfo.CurrentCulture;
    DateTimeFormatInfo dtfi = (DateTimeFormatInfo) current.DateTimeFormat.Clone();
    // I'm not *sure* whether this is necessary
    dtfi.Calendar = (Calendar) dtfi.Calendar.Clone();
    dtfi.Calendar.TwoDigitYearMax = 1910;
    

    Then use dtfi in your call to DateTime.ParseExact.

    Practical way of doing this: add "20" to the start of your input, and parse with "yyyyMMdd".

提交回复
热议问题