Problem:
I am working on a web form that has a date input field, the date is entered as a string and then converted to a date for storage.
This is ok if the users only enter dates in one format, that of the hosting server, but the page is on the internet and could be viewed anywhere, it would be nice if users say in the USA could enter their dates in their own format.
The server is always in uk format, so any culture changes wil have to be in the UK
What I have Found
CultureInfo class can be used to format an item to a specific item.
[
Test] public void ConvertString(){
string usaDate = "12/30/2005"; DateTime ukDate = Convert.ToDateTime("30/12/2005"); DateTime nDate = Convert.ToDateTime(usaDate, new CultureInfo("en-US"));
Console.WriteLine("USA Date: {0}", nDate.ToString(new CultureInfo("en-US")));
Console.WriteLine("UKDate: {0}", nDate.ToString(new CultureInfo("en-GB")));
Assert.AreEqual(nDate, ukDate);
}
So if the input string is in USA format to put it into a datetime object on the server you use
DateTime date = Convert.ToDateTime(usaDateString(new CultureInfo("en-US")));
printing out the date object will print in uk format, as thats what the computer is setup as.
to output back to the form in usa format use
txtDate.Text = date.ToString(new CultureInfo("en-US"));
CultureInfo implements the IFormatProvider