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);
I would strongly suggest that as you know the format in advance, you use
TryParseExactinstead ofTryParse:Note that you should check the return value of
TryParseExactto check that it’s parsed correctly – if you’re fine with an exception, just useParseExactinstead.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.