chobo2
chobo2

Reputation: 85725

DateTime Conversion with Different Cultures

I am wondering what is the best way to figure out how to convert a datetime? Right now my computer is setup as dd/mm/yyyy yet I am taking date as mm/dd/yyy so when I try to do

DateTime.Convert();
DateTime.Parse();
DateTime.TryParse();

I either get nothing back or it crashes. Now I could tell it about the mm/dd/yyyy format and it probably would convert. However the problem is these dates are are coming from user uploaded files.

They could be in any format combination. I am trying to find ways to do it.

The problem I see is that I am looking at the dates in an uploaded file so I am not sure if looking say at the browser date format would help or not.

I am using asp.net mvc and I am trying to get a solution that handle date formats automatically so I don't have to ask the user about the date format they have (I figure the more things I have to ask them the less likely the user will continue on)

Upvotes: 3

Views: 2700

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

No, you can't figure out automatically what date-time format a user meant to use once the value is on the server. You need more information to parse it correctly (e.g. 1/2/3 can mean a lot of different dates depending on the culture).

Consider one of the following solutions:

  1. Convert the entered date to a text representation in a standard format (i.e. ISO 8601 - 2012-02-09) using JavaScript on the client before you send it to the server. The code would look something like this: d.getUTCFullYear()+"-" + d.getUTCMonth() + "-" + d.getUTCDate().
  2. Send the local culture information to the server along with date value to be converted and do the conversion on the server.
  3. Force the user to enter the date in a specific format (e.g. Use 3 text boxes labeled "Month", "Day", and "Year" instead of one text box with free input).

Upvotes: 1

jim tollan
jim tollan

Reputation: 22485

chobo2 (I like the 'handle') :)

you can detect the locale culture and work on that at will. see the following SO Q/A for pointers:

Where is the system locale/culture set for .Net

the key is to NOT have to set anything in particular, but identify the locale and act accordingly.

Upvotes: 1

Related Questions