-4

I have a string and when I try to convert that to a DateTime it's throwing an error. Why?

string str = "3‎/‎23‎/‎2016‎ ‎5‎:‎10‎:‎32‎ ‎PM";
datetime= convert.ToDateTime(str);
juharr
  • 31,741
  • 4
  • 58
  • 93
poc
  • 183
  • 2
  • 3
  • 14
  • 5
    Use `DateTime.Parse` – BWA Mar 23 '16 at 11:51
  • Either add a leading "0" before your month or use DateTime.Parse – Koby Douek Mar 23 '16 at 11:52
  • 1
    Well, reading the error message (that you don't want to show us?) will give you a hint. You probably need to define the culture to use for parsing. – René Vogt Mar 23 '16 at 11:52
  • String was not recognized as a valid DateTime.Parse id again throwing error" String was not recognized as a valid DateTime" ; DateTime dt = DateTime.Parse(str); – poc Mar 23 '16 at 11:54
  • 1
    @BWA according to msdn `Convert.ToDateTime` uses `DateTime.Parse`, so that won't help. – René Vogt Mar 23 '16 at 11:54
  • you are missing leading 0 of hour – Ehsan Sajjad Mar 23 '16 at 11:56
  • 2
    Possible duplicate of [String was not recognized as a valid DateTime " format dd/MM/yyyy"](http://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy) – o_weisman Mar 23 '16 at 11:57
  • Possible duplicate of [Converting a String to DateTime](http://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – Meiko Rachimow Mar 23 '16 at 12:12
  • 2
    This is not a duplicate, and `Convert.ToDateTime` should work fine if his culture has that format. The problem is quite different. – Jcl Mar 23 '16 at 12:14
  • Please check before saying that , its duplicate :) – poc Mar 23 '16 at 13:42

1 Answers1

3

Convert.ToDateTime should work fine if your current culture allows this.

You however have some strange characters in your string... I have copied and pasted it and it didn't work, however writing it directly did.

Check it in a fiddle: https://dotnetfiddle.net/l5nzso

It seems you have some left-to-right mark (0x200E) Unicode characters scattered between the characters in your string. Check it in this other fiddle

Jcl
  • 27,696
  • 5
  • 61
  • 92
  • I just noticed the same thing. The length shows as 32 instead of 20. – juharr Mar 23 '16 at 12:08
  • 1
    It seems there are some [left-to-right mark (0x200E)](http://www.fileformat.info/info/unicode/char/200e/index.htm) unicode characters scattered in the string, pretty weird – Jcl Mar 23 '16 at 12:12
  • 1
    The left-to-right mark characters could be replaced to make this work `str = str.Replace(new string((char)8206, 1), string.Empty);` – juharr Mar 23 '16 at 12:21
  • @Jcl , Awesome findings, how can I remove those Unicode characters. – poc Mar 23 '16 at 14:31
  • @juharr gave you the solution right in the comment above yours – Jcl Mar 23 '16 at 14:32