Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

c# - How to check if date is less than or equals to today's date?

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

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?

Code:

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
{
}

You can have your method as:

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;
}
  • 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...