I have an ASP.NET web application which is multi culture meaning I have en-us
, en-ca
, fr-ca
, etc.
My problem is when I am trying to Parse a date 1/22/2014
using DateTime.Parse
and I am using en-us
, it will work because the ShortDatePattern
of en-us
is M/dd/yyyy
but if the user is en-ca
, the ShortDatePattern
is dd/MM/yyyy
.
How can I parse the dates considering different cultures? I have tried the following codes:
DateTime.Parse(date);
DateTime.ParseExact(date, ShortDatePattern, Culture);
DateTime.TryParseExact(date, ShortDatePattern, Culture, DateTimeStyles.None, out date);
But still no luck for me.
EDIT
DateTime.Parse
throws me an exception, string is not a valid datetime. Same with the DateTime.ParseExact
. DateTime.TryParseExact
give me a date of 1/1/0001.
If you're absolutely sure of the user's culture - and that they'll actually use that - you could use:
// I assume that Culture is a valid reference to a CultureInfo...
DateTime date = DateTime.Parse(date, Culture);
However, I'd strongly consider providing a calendar control or separate year/text-month/day fields on the page (with validation) so that what you post back to ASP.NET can be a machine-readable, culture-neutral date format, e.g. yyyy-MM-dd
. Basically, turn the culture-sensitive representation into a culture-neutral representation as early as you can.
See more on this question at Stackoverflow