How to check if date is less than or equals to today's date?
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.
You could use TryParse
of TryParseExact
which returns bool
, whether parse succeeded or not.
In my first implementation I threw exception, but it is useless, because Parse
or ParseExact
will throw it automatically if fails. So there is two options:
Just use
Parse
and catch exceptions inMain()
;Use
TryParse
and do something useful inIsDateBeforeOrToday()
if input is wrong.
Implementation:
class Program
{
public static bool IsDateBeforeOrToday(string input)
{
DateTime inputTime;
var parseResult = DateTime.TryParse(input, inputTime);
if (!parseResult)
//Do something useful if parse failed.
return inputTime <= DateTime.Now
}
static void Main(string[] args)
{
Console.WriteLine(IsDateBeforeOrToday("03/26/2015"));
Console.ReadKey();
}
}
You could use the DateTime.Compare method. You could do this:
DateTime dTCurrent = DateTime.Now;
DateTime inputDate = DateTime.ParseExact(input, "MM/dd/yyyy", CultureInfo.InvariantCulture);
int result = DateTime.Compare(dTCurrent, inputDate);
The int 'result' would indicate if dTCurrent is less than inputDate (less than 0), same as (0) or greater than (greater than 0).