CultureInfo

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

 

 

 

 

Advertisements

About Duncan Butler

Trying to be a very agile software developer, working in C# with Specflow, Nunit and Machine Specifications, and in the evening having fun with Ruby and Rails
This entry was posted in Code. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s