I have a asp.net textbox for date input, I use regular expression to let the user input date in dd-mm-yyyy format but when i convert the input date in datetime object, the month and day values are interchanged. How can a specify the right way for interpreting this input date?
You can accomplish this by specifying a culture that uses the format dd-mm-yyyy like Germany:
DateTime dateTime = DateTime.Parse("01-12-2009", CultureInfo.GetCultureInfo("de-DE"));
Console.WriteLine(dateTime.ToString("dd MMM yyyy"));
produces:
01 Dec 2009
Of course, you really want to do all of your culture specific processing in the culture of your user. So, CultureInfo.GetCultureInfo("de-DE")
should be CultureInfo.CurrentCulture
.
And if your user isn't used to seeing dates like dd-mm-yyyy, then don't use that format.
I've used DateTime.Parse() in the past.
But it sounds like you are have culture issue, so this approach might be better:
// Parse a date and time with no styles.
dateString = "03/01/2009 10:00 AM";
culture = CultureInfo.CreateSpecificCulture("en-US");
styles = DateTimeStyles.None;
try
{
result = DateTime.Parse(dateString, culture, styles);
outputBlock.Text += String.Format("{0} converted to {1} {2}.",
dateString, result, result.Kind.ToString()) + "\n";
}
catch (FormatException)
{
//Error
}
More info on msdn: http://msdn.microsoft.com/en-us/library/ey1cdcx8(VS.96).aspx
But you could also build the date time up if that works better:
DateTime d = new DateTime(Y, M, D);
I'm suggesting to use DateTime.TryParseExact() and specify your date format.
It sounds like the app is running under a different culture to what you are expecting as user input. You might want to change the culture to the one you are expecting.