DateTime string parsing

前端 未结 3 1812
逝去的感伤
逝去的感伤 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:21

    You will need to determine some kind of threshold date appropriate for your data. If the parsed date is before this date, add 100 years. A safe way to do that is to prefix the input string with the appropriate century. In this example I've chosen 1970 as the cutoff:

    string input = ...;
    DateTime myDate;
    
    if (Convert.ToInt32(input.Substring(0, 2)) < 70)
        myDate = DateTime.ParseExact("20" + input, ...);
    else
        myDate = DateTime.ParseExact("19" + input, ...); 
    

    Jon Skeet also posted a nice example using DateTimeFormatInfo that I had momentarily forgotten about :)

提交回复
热议问题