0 votes
by (2.0k points)
I have a date like :

5/1/2021

This date is actually the 5th of Jan, but when I run my C# code, it actually parses it as the 1st of May. How can I make it always read the first part of the date as days, and the second part as months?

1 Answer

0 votes
by (2.0k points)

The way DateTime.Parse() works is mostly dependant on the environment/culture that the code is running in. So, especially if you have non-USA and USA based servers, you can get wildly different results. 

The best way, assuming that the dates are always in the same format, is to use DateTime.ParseExact, you can use it like so : 

DateTime datetime = DateTime.ParseExact(myDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

DateTime.ParseExact is pretty self explanatory, but it basically parses the date in the format exactly how you specify it should. It can be finicky if you also want to parse times since you'll need to add those to the exact string format, but otherwise it's probably your best option here. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...