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();
}
}
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).
To check if a date is today's date:Use the Date() constructor to get today's date. Compare the output of the getFullYear() , getMonth() and getDate() methods for the dates. If the year, month and day values are equal, then the date is today's date.
Example 2: Python Compare with Two Datesstrptime(secondDate, "%Y-%m-%d") if oneDateObj. date() > secondDateObj. date(): print("First Date is Greater...") else: print("Second Date is Greater...")
Compare() Method in C# This method is used to compare two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.
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;
}
DateTime.TryParseExact
if you want to avoid exception in
parsing.DateTime.Today
if you only want to compare date and ignore the
time part.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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With