Alexandre
Alexandre

Reputation: 13328

Unable to parse DateTime from a string

string dt = "10/25/2010 11:40:05 PM";
var currentThread = Thread.CurrentThread.CurrentCulture; //ru-RU
DateTime dateTime = DateTime.Parse(dt); //Exception!

How to parse that dt?

UPDATE: In my case DateTime can be represent as "25.10.2010 11:40:05" or "10/25/2010 11:40:05 PM" Is these any "generic" method to parse it without changing CurrentCulture?

Upvotes: 0

Views: 4619

Answers (6)

Jon Skeet
Jon Skeet

Reputation: 1503729

Russia doesn't use AM and PM as their AM/PM designators, which is at least one reason that would fail. Another is that Russia may not use the "month/day/year" format which is mostly a peculiarity of the US as far as I'm aware. (I can't remember Russia's format strings offhand; I do remember that the genitive month names caused me grief recently, but that's another story...)

I would personally explicitly specify the culture as the invariant culture, and also explicitly specify the format string:

string text = "10/25/2010 11:40:05 PM";
string pattern = "MM/dd/yyyy hh:mm:ss tt";
DateTime dt = DateTime.ParseExact(text, pattern,
                                  CultureInfo.InvariantCulture);

If this might reasonably be expected to fail, you should use DateTime.TryParseExact instead, to handle failure gracefully without involving exceptions.

Upvotes: 1

Oded
Oded

Reputation: 499382

Use a custom Date and Time format string, using either ParseExact or TryParseExact.

DateTime dateTime;
DateTime.TryParseExact(
                       dt, 
                       "MM/dd/yyyy hh:mm:ss tt", 
                       CultureInfo.InvariantCulture,
                       DateTimeStyles.None,
                       out dateTime
                      );

The string cannot be parsed as a Russian DateTime representation since the Russian culture doesn't use AM/PM, hence the use of the use of CultureInfo.InvariantCulture which is a US like culture (it represents no specific culture, but is modeled after the en-US one).

Upvotes: 5

Wojteq
Wojteq

Reputation: 1183

Try something like this:

dateTime = DateTime.Parse(dt, CultureInfo.CreateSpecificCulture("en-US"));

Upvotes: 0

sll
sll

Reputation: 62554

var result = DateTime.ParseExact(dt, 
                                 "MM/dd/yyyy hh:mm:ss tt", 
                                 CultureInfo.InvariantCulture);

To avoid runtime exceptions use safe DateTime.TryParseExact() method, it returns false in case of unsuccessfull parsing rather than throwing the FormatException exception

Upvotes: 1

James Johnson
James Johnson

Reputation: 46067

Try using ParseExact instead:

DateTime myDate = DateTime.ParseExact("10/25/2010 11:40:05 PM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Upvotes: 2

CassOnMars
CassOnMars

Reputation: 6181

Try DateTime.Parse(dt, CultureInfo.GetCultureInfo("EN-us"))

Upvotes: 1

Related Questions