0

I am using the following code for Short date validation.

DateTime dt = DateTime.Now;
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR");
if (DateTime.TryParse(textBox1.Text, out dt))
{ textBox1.Text = dt.ToShortDateString(); }

But there is a small Problem, If user enters 1/1/1 the output looks like 01/01/2001.

if user enter 1-1-1 the output looks like 01/01/2001. Because of Format given by me.

now what i want if user enter like 1-1-1 the output should be 01-01-2001.

John Koerner
  • 37,428
  • 8
  • 84
  • 134
sree aneev
  • 141
  • 4
  • 5
  • 18
  • Try to use maked textbox.... Its a better option.... – Sagar Upadhyay Mar 09 '13 at 08:12
  • No matter what format user enters the date -> after the string is parsed to DateTime -> it's displayed always the same way. Because it's the same DateTime value -> only the input was different. – ub1k Mar 09 '13 at 08:17
  • @sree aneev so you want to get the output according to input right? means if you enters 1/1/1 you want 01/01/2001 and if user enters 1-1-1 you want 01-01-2001. is that so??? – kashif Mar 09 '13 at 09:20
  • @kashif right i want like that is there any chance... – sree aneev Mar 09 '13 at 18:25

2 Answers2

2

Try this:

dt.ToString(@"dd-MM-yyyy");

And if you want to diferentiate the output according to the input, I would suggest this:

if (textbox1.Text.Contains("/"))
{
    textBox1.Text = dt.ToString(@"dd/MM/yyyy");
}
else
{
    textBox1.Text = dt.ToString(@"dd-MM-yyyy");
}
Matus
  • 410
  • 5
  • 15
  • for this 1/1/1 what can i do i want both as per the user – sree aneev Mar 09 '13 at 18:26
  • @Matus It is me who upvoted you for your answer. But as opposed to this I ask the questioner why doesn't he use MaskTextBox. If I were him, I would never use TextBox for Date purpose atleast. – kashif Mar 09 '13 at 20:30
0

I don't understand why you are using TextBox instead of MaskedTextBox in such condition. I would recommend you use MaskedTExtBox for this. Drag and Drop two MaskedTextBox from ToolBox to your Form and in the FormLoadEvent use this code

maskedTextBox1.Mask = "##/##/####";
maskedTextBox2.Mask = "##-##-####";
kashif
  • 3,713
  • 8
  • 32
  • 47
  • Note: I have used Two MaskedBoxes to show you that you can use any type of your desired format. you can even set it manual according to you requirement. – kashif Mar 09 '13 at 20:32
  • but he wants to format the date in two different ways according to the user input in the same textbox – Matus Mar 10 '13 at 08:43
  • just try one thing @kashif if he enter 1/1/1 what should be the answer for your first "##/##/####" for the above one the answer should be 1//1//1. it is wrong. – sree aneev Mar 10 '13 at 14:43