如何检查日期是否小于或等于今天的日期? [英] How to check if date is less than or equals to today's date?

查看:142
本文介绍了如何检查日期是否小于或等于今天的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定用户输入的日期是否小于或等于今天的日期.

I need to determined if the date entered by the user is less than or equals to today's date.

我有以下代码将日期转换为 int ,然后比较它们的值.有没有更有效或精益的方法来用更少的代码行来完成此任务?

I have the following code which converts the dates to int and than compare their values. Is there a more efficient or lean way to get this accomplished with less lines of code?

如何用更少的代码或多余的代码来做到这一点?

How do I do this with far less code or extraneity?

代码:

class Program
{
    public static bool IsDateBeforeOrToday(string input)
    {
        bool result = true;

        if(input != null)
        {
            DateTime dTCurrent = DateTime.Now;
            int currentDateValues = Convert.ToInt32(dTCurrent.ToString("MMddyyyy"));
            int inputDateValues = Convert.ToInt32(input.Replace("/", ""));

            result = inputDateValues <= currentDateValues;
        }
        else
        {
            result = true;
        }

        return result;
    }

    static void Main(string[] args)
    {
        Console.WriteLine(IsDateBeforeOrToday("03/26/2015"));
        Console.ReadKey();
    }
}

推荐答案

与其将当前日期转换为字符串,然后将 int 转换为字符串,然后将参数日期字符串转换为 DateTime 对象,然后进行比较:

Instead of converting current date to string and then int and doing the comparison, convert your parameter date string to DateTime object and then compare like:

var parameterDate = DateTime.ParseExact("03/26/2015", "MM/dd/yyyy", CultureInfo.InvariantCulture);
var todaysDate = DateTime.Today;

if(parameterDate < todaysDate)
{
}

您可以将方法设置为:

public static bool IsDateBeforeOrToday(string input)
{
    DateTime pDate;
    if(!DateTime.TryParseExact(input, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out pDate))
    {
        //Invalid date
        //log , show error
        return false;
    }
    return DateTime.Today <= pDate;
}

  • 如果要避免以下情况中的异常,请使用 DateTime.TryParseExact 解析.
  • 如果您只想比较日期而忽略日期,请使用 DateTime.Today 时间部分.
    • Use DateTime.TryParseExact if you want to avoid exception in parsing.
    • Use DateTime.Today if you only want to compare date and ignore the time part.
    • 这篇关于如何检查日期是否小于或等于今天的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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