Reputation: 1142
I have an ASP.NET / C# web site i'm building, in one of the pages i'm asking the user to choose a date with a date picker of my own which send the date to my code-behind in "dd/MM/yyyy" format.
The problem starts when the site is online, my computer is using the "dd/MM/yyyy" format and the server uses the "MM/dd/yyyy" format, so when i try to convert the date received in the code-behind to a DateTime type using "Conver.ToDateTime()" on my own PC it works just fine, but when the site is online, if the date is for example "14/05/2015" it will cause an 'String was not recognized as a valid DateTime.' error, since it's trying to convert it to a format which causes it to be an illegal date (5th day of 14th month).
What's the best elegant solution for this problem? Thanks.
Upvotes: 0
Views: 504
Reputation: 735
I've had the best experience formatting the date with ISO format. It is well-defined and can't possibly get confused.
For example:
DateTime.Now.ToString("o")
This will produce:
2015-07-04T16:56:54.2508072+01:00
To be double-sure, you can always parse it back this way:
DateTime.ParseExact(dateAsStr, "o", CultureInfo.InvariantCulture)
Upvotes: 0
Reputation: 887469
You need to pass a specific CultureInfo
or format string to all of your date parsing and ToString()
calls.
Upvotes: 1
Reputation: 3785
Send the date in a fixed format, like ISO (yyyy-MM-dd
). If all parties use the same format, there will be no ambiguity.
Upvotes: 1