-1

I have a string returned from an api call . The string is : 11/25/2021 05:20:21

Now that is a mm/dd/yyyy hh:mm:ss

I want to compare it to the datetime 2021-11-25 05:03:17.667

I do the following:

var dt1="11/25/2021 05:20:21";
var dt2= "2021-11-25 05:03:17.667"

DateTime date1 = Convert.ToDateTime(dt1);
DateTime date2 = Convert.ToDateTime(dt2);

int result = DateTime.Compare(date1, date2);
if (result < 0)
{
 //d1 is earlier than d2.
}

but when i do the call DateTime date2 = Convert.ToDateTime(dt2); it gives an error , string is not in the correct format ?

Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
Kylie
  • 95
  • 1
  • 12
  • 1
    DateTime.ParseExact is the one to use. Here is an example https://dotnetfiddle.net/LuZOzP – j4jada Nov 25 '21 at 06:22
  • what if the var dt1="11/25/2021 05:20:21 AM"; do i just strip off the AM. I just did this dt1.Replace("AM", "").Replace("PM", ""); ? – Kylie Nov 25 '21 at 06:42
  • if i have a time as "25/11/2021 6:20:25 AM" no 0 infront of the hour it gives error . How can i put a 0 infront when i get the time ? – Kylie Nov 25 '21 at 07:06

1 Answers1

0

You should probably use DateTime.ParseExact, which allows you to provide an excat format to parse your string.

san1127
  • 153
  • 2
  • 9
  • have tried doesnt seem to give me the result . the dates can come in different formats , so i cant really set a format. I have tried usig a pattern of string pattern = "yyyy-dd-MM h:mm tt zzz"; – Kylie Nov 25 '21 at 06:04
  • @Kylie If you have multiple possible format, the only thing you can do is to call ParseExact with different format parameters one by one and make sure at lease one of them works. – san1127 Nov 26 '21 at 14:29