Mike
Mike

Reputation: 3284

DateTime Parsing .Net 3.5

I have a string in my DB2 database which is physically located in US. I have a column value set to this string '2011-12-31 00:00:00' which indicates year 2011, month december and day 1st of the december.

I'm retrieving this as a string in my client program which is running in UK and the UI is set to local culture(the default). My client program also runs in US as well as in Hongkong with the culture set to the local culture there i.e US and HK respectively.

I'm using the following code for parsing the string into a datetime. I'm not very sure whether this is going to work, and I could't find any good link which points me to that direction. Could you please tell me whether this will work in various cultures, if not why?

string quarterStartDate = "2011-12-01 00:00:00";
DateTime quarterStart;
DateTime.TryParse(quarterStartDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out quarterStart);
return quarterStart;

I have a test which works as per my requirement, but again 'am not too sure whether this will work when the UI is going to run in a different country.

  string quarterStarter = "2011-12-01 00:00:00";        
  DateTime quarterStart; 
  DateTime.TryParse(quarterStarter,CultureInfo.InvariantCulture,DateTimeStyles.None,out quarterStart);    
  Assert.IsTrue(quarterStart.Year == 2011);
  Assert.IsTrue(quarterStart.Month == 12);
  Assert.IsTrue(quarterStart.Day == 1);

Upvotes: 0

Views: 366

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500055

I would strongly suggest that as you know the format in advance, you use TryParseExact instead of TryParse:

bool success = DateTime.TryParseExact(quarterStarter, "yyyy-MM-dd HH:mm:ss",
                                      CultureInfo.InvariantCulture,
                                      DateTimeStyles.None,
                                      out quarterStart);

Note that you should check the return value of TryParseExact to check that it's parsed correctly - if you're fine with an exception, just use ParseExact instead.

It's entirely possible that your existing code would work just fine - after all, you're already providing the invariant culture - but specifying the format makes it clearer what you really expect, and also means you'll detect if a value in an unexpected format is provided.

Upvotes: 2

Luis Tellez
Luis Tellez

Reputation: 2973

You can set a specific format that does not change with culture.

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

Upvotes: 1

Lloyd
Lloyd

Reputation: 29668

You can use ParseExact to pull the date, for example:

var s = "2011-12-01 00:00:00";
var dt = DateTime.ParseExact(s,"yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture);

Upvotes: 1

Related Questions