【问题标题】:A C# function to check a date from day month year一个 C# 函数,用于从日月年检查日期
【发布时间】:2013-01-23 19:53:36
【问题描述】:

我有三个字符串/整数,分别是日、月和年。有什么方法可以检查它们是否采用有效的 DateTime 格式?我正在使用 ASP.NET。

当用户注册时,他会输入月、日和年。

我曾经将三个变量转换为字符串并尝试解析以检查它是否合法,但唯一的问题是在不同的机器上运行相同的项目,因为一些不同的机器使用不同的日期格式。

【问题讨论】:

  • TryParse 有一个重载,可让您指定文化(文化定义日期格式)。
  • 在这些机器上,您在解析时设置区域设置。
  • 考虑使用DateTime.ParseExact,可以将日期格式设置为参数。
  • 如果您 TryParse 使用 CultureInfo.InvariantCulture 作为格式提供者,以确保忽略机器的“自己的”日期格式。

标签: c# asp.net date datetime


【解决方案1】:

这个怎么样:

    private bool IsValidDate(int year, int month, int day)
    {
        if (year < DateTime.MinValue.Year || year > DateTime.MaxValue.Year)
            return false;

        if (month < 1 || month > 12)
            return false;

        return day > 0 && day <= DateTime.DaysInMonth(year, month);
    }

【讨论】:

  • 这比使用 try catch 异常要好得多。
【解决方案2】:

如果你已经有daymonthyear三个独立的int,你可以直接使用one of DateTime's constructors,而不是把它们转换为字符串并将其重新解析为 DateTime。

DateTime mydate;
myDate = new DateTime(year, month, day);

如果日期无效,这将抛出 ArgumentOutOfRangeException,因此您应该将其包装在 try/catch 块中,并在日期格式无效时使用 catch(ArgumentOutOfRangeException e) 块来管理逻辑。

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    相关资源
    最近更新 更多