maitiest
maitiest

Reputation: 149

Correct Date Format Validation of a Date

Label gdate=(Label)(GridView1.Rows[i].FindControl("Date"));

Now what i want is to make sure that the date(or value) in variable gdate is a valid date(ShortDate like 14-03-2014) without time (not like 14-03-2014 00:00:00 which is invalid)

Upvotes: 1

Views: 383

Answers (5)

VIPUL PARMAR
VIPUL PARMAR

Reputation: 292

Try this one to store formated date

string chkin = txtCheckIn.Text;
DateTime CheckIn = DateTime.ParseExact(chkin, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 0

visorvice1
visorvice1

Reputation: 64

Try this

gdate.Text = DateTime.Now.Date.ToShortDateString();

Upvotes: 0

Use DateTime TryParseEaxct if the exact format needs checking:

DateTime dateValue
if (DateTime.TryParseExact(gdate.Text, "dd-MM-yyyy", null, 
                       DateTimeStyles.None, out dateValue))
{
    //Date in correct format
    //use dateValue
}
else
{
    //Date in incorrect format
}

Convert.ToDateTime will throw an exception if the datetime cannot be parsed.

ParseExact will also throw an exception if the date string in your Date control is empty.

Upvotes: 1

J R B
J R B

Reputation: 2136

You can use short date function for date format, like

 DateTime dt=new DateTime();
 dt = DateTime.Now;
 MessageBox.Show(dt.ToShortDateString());

Upvotes: 0

Dgan
Dgan

Reputation: 10295

A CustomValidator here:

<asp:CustomValidator runat="server"
    ID="valDateRange" 
    ControlToValidate="txtDatecompleted"
    onservervalidate="valDateRange_ServerValidate" 
    ErrorMessage="enter valid date" />

Server Side:

protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
    DateTime minDate = DateTime.Parse("1000/12/28");
    DateTime maxDate = DateTime.Parse("9999/12/28");
    DateTime dt;

    args.IsValid = (DateTime.TryParse(args.Value, out dt) 
                    && dt <= maxDate 
                    && dt >= minDate);
}

Upvotes: 0

Related Questions