Vijay Rana
Vijay Rana

Reputation: 143

Convert String "7/16/2013 7:00:00 AM" to DateTime

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

Answers (3)

Alois Kraus
Alois Kraus

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

  • M Month 0-12 number without leading zeros
  • d Day number 0-31 without leading zeros
  • yyyy Year with all digits
  • M Hour in 12h format 0-12 without leading zeros
  • mm Minutes 0-59 with leading zeros
  • ss Seconds 0-59 with leading zeros

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

Vivek Jain
Vivek Jain

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

Adel Khayata
Adel Khayata

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

Related Questions