如何从DatePicker计算年龄?

时间:2019-01-02 02:05:44

标签: c# xamarin xamarin.forms

我正在尝试验证用户的年龄足以使用我的应用程序(> 15)。在我的应用中,用户必须在注册期间设置他/她的出生日期。据此,我想计算年龄以检查用户是否足够大。

XAML代码:

<Label Text="Date Of Birth"/>
            <DatePicker BackgroundColor="White" Date="{Binding DateSelected}"/>
            <Label TextColor="Red" Text="You have to be at least 15 years old" IsVisible="{Binding TooYoung}"/>

我正在使用模式MVVM绑定DateIsVisible。因此,如果用户年龄不够大,则应显示第二个标签。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下代码:

    public bool TooYoung { get; set; }

    private DateTime _DateSelected;

    public DateTime DateSelected
    {
        get { return _DateSelected; }
        set
        {
            if (_DateSelected.Equals(value))
            {
                return;
            }

            _DateSelected = value;

            // check someone is too young or not
            var age = CalculateAge(_DateSelected);
            TooYoung = age <= 15;
        }
    }

    private int CalculateAge(DateTime birthDay)
    {
        int years = DateTime.Now.Year - birthDay.Year;

        if ((birthDay.Month > DateTime.Now.Month) || (birthDay.Month == DateTime.Now.Month && birthDay.Day > DateTime.Now.Day))
            years--;

        return years;
    }

答案 1 :(得分:0)

var difference = DateSelected.subtract(DateTime.Today);
if (difference.TotalDays <= 5475){
    //Trigger error event
}

希望这会有所帮助。