Wednesday, April 19, 2006

Convert String to Date and check Date Validation on Server side in C#.Net.

Convert String to Date and check Date Validation on Server side in C#.Net.

There are lots of functions available in client side for date validation.
Sometime server side date validation function require
It’s very simple but require much time to right. (C#.Net)

SupportedDateFormats : It is a customise function where you can refer the date format whatever you want.

ConvertStringToDate : This will return True or Flase based on date format supported. And give converted Date from String.

public static bool ConvertStringToDate(string dateString, ref DateTime resultDate)
{
try
{
resultDate = DateTime.ParseExact(
dateString,
SupportedDateFormats(),
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.None
);
return true;
}
catch
{
return false;
}
}

//This is custom defined format function you can add more date format as per your requirement
like "dd/MM/YYYY", etc in the allFormats array
private static string[] SupportedDateFormats()
{
string[] allFormats = new string[] {
"MM/dd/yyyy",
"MM/dd/yy",
"M/d/yy",
"MM/d/yy",
"M/dd/yy",
"M/d/yyyy",
"MM/d/yyyy",
"M/dd/yyyy"};
return allFormats;
}

// Now you can use this function in your code like this
private void button1_Click(object sender, EventArgs e)
{
DateTime dtTemp;
dtTemp =DateTime.Today.Date;
lblIsvalidDate.Text =
ConvertStringToDate(
textBox2.Text,
ref dtTemp
).ToString();
lblCovertedDate = dtTemp.ToString();
}

Note:
If you want this code in VB.Net I would like to tell you very good site that will

4 comments:

nrps said...

I love your code mate Keep up the good work

suda said...

good work

Hari Krishna B said...

it looks very easy & good example and keep it up...

Anonymous said...

Amiable fill someone in on and this enter helped me alot in my college assignement. Thank you on your information.