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 can i parse a string to datetime in c#?

I have a string 02/12/2022 06:53:43 and i want to parse it to a datetime to perform the following check

 string myDate = "02/12/2022 06:53:43";
 DateTime.Parse(myDate).AddMinutes(-2) < DateTime.UtcNow) 

But it gives an error : String was not recognized as a valid DateTime.

How can i parse the date ?

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 :

Is this 12th of Feb or the 2nd of December? 😉

You could use ParseExact. There are plenty examples in DateTime.ParseExact Method.

Here something that works for your format, assuming it’s the 2nd of December.

var dateString = "02/12/2022 06:53:43";
var format = "dd/MM/yyyy hh:mm:ss";
var result = DateTime.ParseExact(dateString, format, 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