Reputation: 143
I am shoked why its giving me an error
Convert.ToDateTime("7/16/2013 7:00:00 AM");
but works fine if i use
Convert.ToDateTime(("16/7/2013 7:00:00 AM");
How can i convert "7/16/2013 7:00:00 AM" to DateTime
Upvotes: 2
Views: 2458
Reputation: 13535
You can either use a specific locale or you can define the format by yourself like this:
var dt = DateTime.ParseExact("7/16/2013 7:00:00 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
I have used
As culture I did specify invariant culture which is basically English on all systems. It is the same regardless of the current culture of the system or the thread.
Your problem did arrise from the fact that you did try to process dates from different locales with the same thread locale from your system which seems to be English. To correctly treat the dates you need to know in which locale it was entered to be able to correctly parse it. Some locales do switch e.g. month and days as it was in your example. Some use different separaters and even other cultures have different uses for the . , chars as thousand separators and decimal point.
German uses , as decimal point and . as thousand separator. A date would look like
"24.12.2013 14:25:59"
No AM/PM no / but many dots.
Upvotes: 7
Reputation: 3889
You may simply try to use DateTime.TryParse()
DateTime dt;
if(DateTime.TryParse("7/16/2013 7:00:00 AM", out dt))
Console.Write(dt);
Upvotes: 0
Reputation: 2836
You have to be aware about the culture, refer to this link : Convert.ToDateTime Method
CultureInfo culture = new CultureInfo("en-US");
Convert.ToDateTime("7/16/2013 7:00:00 AM", culture );
Upvotes: 1