在C#中使用TryParseExact将字符串解析为DateTime [英] Parsing String to DateTime with TryParseExact in C#

查看:367
本文介绍了在C#中使用TryParseExact将字符串解析为DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了很多例子,并且按照他们的建议去做,但是我不断收到 InvliadCastException ,错误描述为:

I've looked at so many examples, and I am doing as they all suggest, yet I keep getting an InvliadCastException with error description of:


无法将类型为'System.DateTime'的对象转换为类型为'System.String'

Unable to cast object of type 'System.DateTime' to type 'System.String'

我要从ASP.NET MVC4应用程序中的出生日期文本字段中获取日期,格式为 1986/9/20

I am getting my date from a Date Of Birth Text field in an ASP.NET MVC4 application, in the following format 20/09/1986

这是我的代码,我只希望18岁以上的用户能够注册。

Here is my code, I only want users above 18 years of age to be able to register.

public class AgeValidator : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        string format = "dd/MM/yyyy HH:mm:ss";
        DateTime dt;
        DateTime.TryParseExact((String)value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);


        DateTime today = DateTime.Today;
        int age = today.Year - dt.Year;
        if (dt > today.AddYears(-age)) age--;

        if (age < 18)
        {
            return false;
        }

        return true;
    }
}

然后使用我的自定义验证,如下所示:

My custom validation is then used like so:

[Required]
[Display(Name = "Date Of Birth")]
[AgeValidator(ErrorMessage="You need to be at least 18 years old to vote.")]
public DateTime DateOfBirth { get; set; }

如何正确解析DateTime?

How can I get the DateTime parsed correctly?

推荐答案

这听起来像是使用重载方法的好地方:

This sounds like a good place to use overloaded methods:

public override bool IsValid(DateTime value)
{
    DateTime today = DateTime.Today;
    int age = today.Year - value.Year;
    if (value > today.AddYears(-age)) age--;

    if (age < 18)
    {
        return false;
    }

    return true;
}

public override bool IsValid(string value)
{
    string format = "dd/MM/yyyy HH:mm:ss";
    DateTime dt;
    if (DateTime.TryParseExact((String)value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    {
        return IsValid(dt);
    }
    else
    {
        return false;
    }

}

public override bool IsValid(object value)
{
    return IsValid(value.ToString());   
}

这篇关于在C#中使用TryParseExact将字符串解析为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆