2

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?

2
  • How are you converting to DateTime? Commented Aug 4, 2009 at 13:53
  • I'm using DateTime fromDate = Convert.ToDateTime(this.txtFromDate.Text); Commented Aug 4, 2009 at 13:54

5 Answers 5

1

You can use DateTime.ParseExact

Sign up to request clarification or add additional context in comments.

1 Comment

I used DateTime.ParseExact(this.txtFromDate.Text,"dd-MM-yyyy",CultureInfo.CultureInvariant) be careful with MM capital case letter, coz it's important :-) Thank you
1

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.

Comments

1

I'm suggesting to use DateTime.TryParseExact() and specify your date format.

Comments

0

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);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.