0

I'm making an application where the user has to be more than 18. If he/she is less than 18 a messageBox appears saying "under age". I'm using a datePickerto select the users D.O.B. My problem is I'm not entirely sure on how to code this but I gave it a go by looking at tutorials but all the tutorials seem to be dateTimePickers.

My code is as follows:

xaml

<DatePicker HorizontalAlignment="Center" Name="dpkDOB" Grid.Column="1" VerticalAlignment="Top" Grid.Row="1" />

xaml.cs

 int age = DateTime.Today.Year - tbkDOB.Value.Year;
 if (age < 18)
 {
     MessageBox.Show("Under age");
 }
demonplus
  • 5,613
  • 12
  • 49
  • 68
Craig Gallagher
  • 1,613
  • 6
  • 23
  • 52

1 Answers1

2

I have tested in visual studio. Please find the below working code :

XAML :

<DatePicker HorizontalAlignment="Center" Name="dpkDOB" Grid.Column="1" 
   VerticalAlignment="Top" Grid.Row="1" 
   SelectedDateChanged="dpkDOB_SelectedDateChanged"/>

XAML.cs :

public MainWindow()
{
    InitializeComponent();
}

private void dpkDOB_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
{
    var ageInYears = GetDifferenceInYears(dpkDOB.SelectedDate.Value, DateTime.Today);
    if (ageInYears < 18)
    {
        MessageBox.Show("Under age");
    }
}

int GetDifferenceInYears(DateTime startDate, DateTime endDate)
{
    return (endDate.Year - startDate.Year - 1) +
        (((endDate.Month > startDate.Month) ||
        ((endDate.Month == startDate.Month) && (endDate.Day >= startDate.Day))) ? 1 : 0);
}
ViVi
  • 4,339
  • 8
  • 29
  • 52
  • I'm getting an error saying `datePicker` does not contain definition for value. – Craig Gallagher Jul 28 '16 at 10:59
  • The property you want to use is DisplayDate - check the documentation : https://msdn.microsoft.com/en-us/library/system.windows.controls.datepicker(v=vs.110).aspx – PaulF Jul 28 '16 at 11:03
  • As stated in the original answer here http://stackoverflow.com/questions/4127363/date-difference-in-years-c-sharp, this method is wrong. Luckily, a correct algorithm is given by dana just a little further down, although it has only 19 votes. – Haukinger Jul 28 '16 at 11:28
  • I have tried this but I get a runtime "Ivaled cast from Int32 to DateTime" using this code DateTime zeroTime = new DateTime(1, 1, 1); `DateTime a = Convert.ToDateTime( dpkDOB.SelectedDate.Value.Year); DateTime b = Convert.ToDateTime( DateTime.Today.Year); TimeSpan span = b - a; // because we start at year 1 for the Gregorian // calendar, we must subtract a year here. int years = (zeroTime + span).Year - 1; if (years < 18) { MessageBox.Show("Under age"); }` – Craig Gallagher Jul 28 '16 at 11:32
  • @CraigGallagher : Sorry for the delay. I was out of my desk for quite a long time. I have tested in visual studio and edited my answer and added the working code. Please try that. – ViVi Jul 28 '16 at 18:13