Reputation: 953
I have a string "2/15/50"
that needs to be converted to datetime format and I am using the following code:
DateTime.TryParse("2/15/50", out dt);
The output I am getting is: 02/15/1950 12:00:00 AM
The output expected is: 02/15/2050 12:00:00 AM
Is there a way I can achieve the latter. Suggestions to use other functions are welcome. I tried using Convert.ToDateTime
as well and it returns the same output as TryParse.
Upvotes: 1
Views: 611
Reputation: 787
This should work for you,
CultureInfo ci = new CultureInfo("en-US");
ci.Calendar.TwoDigitYearMax = 2099;
DateTime.TryParse("2/15/50", ci, System.Globalization.DateTimeStyles.None, out DateTime dt)
Heres the documentation on the method, ParseExact allows you to specify the format etc https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=net-5.0
Here is where I got the culture information code https://www.hanselman.com/blog/how-to-parse-string-dates-with-a-two-digit-year-and-split-on-the-right-century-in-c
Upvotes: 5