-1

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 ?

Kelly
  • 81
  • 1
  • 10
  • 1
    Other than the syntax error, [can't reproduce this error](https://dotnetfiddle.net/mc7jiA), please post a [mre], and look at using DateTime.TryParseExact. – gunr2171 Mar 18 '22 at 02:22

2 Answers2

1

Try this:

DateTime date = DateTime.ParseExact("02/12/2022 06:53:43", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
marco
  • 121
  • 1
  • 10
1

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);
tymtam
  • 31,798
  • 8
  • 86
  • 126