DateTime Parse and CultureInfo problem.

D

dotnw

My SQL Server database is held on a server in the USA.
Inside my database table, I have some date values.
They are represented in USA format = month/day/year

If someone looks at my website in the USA, I want them to see dates
represented in USA format. If someone looks at my website in the UK, I
want them to see the date values in UK format which is different to USA
format. It is day/month/year.

I have tried using CultureInfo, ParseExact, and Parse, but every time I
get this error:

String was not recognized as a valid DateTime.

My simple 2 lines of code is below. Please note the "c" variable is
the specific culture info, set to either "en-US" or "en-GB", depending
on which country the user is in. If I set this to "en-GB", then I get
the error.

Dim datReviewDate As DateTime = DateTime.ParseExact("1/31/2004",
"mmddyyyy", c)
Label1.Text = datReviewDate.ToShortDateString
Thanks for any ideas,
Regards, dnw.
 
G

Guest

First of all, you would be better off if the date values in the SQL Server
were stored as datetime values instead. That way you would not have to do
any parsing when reading them from the database.

The DateTime.ParseExact can only parse a string if the format is exactly as
specified. This means that DateTime.ParseExact("1/31/2004", "mmddyyyy") will
not work while DateTime.ParseExact("01/31/2004", "mmddyyyy") works. However,
since the format from the database is a US-format, you can use the following
code to parse a date and output it in UK-format:

string dt = "1/31/2004";
CultureInfo nfo = new CultureInfo("en-US");
DateTime date = DateTime.Parse(dt, nfo);

CultureInfo nfo2 = new CultureInfo("en-GB");
Console.WriteLine(date.ToString(nfo2));

HTH, Jakob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top