Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to parse a string to DateTime in c#?

I want to subtract dt2 (2023-12-31) from dt1 (2023-01-01) in c#, but when i try to debug the codes it says " System.FormatException: ‘String ‘2023-12-31 08:00:00′ was not recognized as a valid DateTime.’ "
can not recognized as a valid DateTime
my codes:

DateTime dt1 = DateTime.Parse("2023-01-01 08:00:00");
DateTime dt2 = DateTime.Parse("2023-12-31 08:00:00");
TimeSpan diff = dt2.Subtract(dt1);
Console.WriteLine(diff.ToString());

How i can fix this error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your issue is not about subtracting DateTimes but the exception happens when you parse them. The reason is that DateTime.Parse uses your current culture’s information(like date-separator) when you don’t pass another. It seems that you are from iran, so this lets reproduce the exception:

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fa-IR");
DateTime dt2 = DateTime.Parse("2023-12-31 08:00:00");

So one way to fix it is to pass CultureInfo.InvariantCulture:

DateTime dt1 = DateTime.Parse("2023-01-01 08:00:00", CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.Parse("2023-12-31 08:00:00", CultureInfo.InvariantCulture);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading