Best way to compare DateTime to run code

What is the best way to compare two DateTime

in a specific format and start code if passed DateTime

.

My DateTime is formatted as 4/26/2017 10:00:00 AM

    DateTime currentDateTime = DateTime.Now;
    DateTime eventDateTime = DateTime.Parse("4/26/2017 10:00:00 AM");

int result = DateTime.Compare(currentDateTime, eventDateTime);

if (result < 0)
    Response.Write( "is earlier than Do Nothing");
else if (result == 0)
    Response.Write("is the same time as: Do Nothing");         
else
    Response.Write("Time is greater, Trigger Action ");

      

Is the code above for comparison purposes or can we improve it.

+3


source to share


3 answers


To compare Dates

, your method is efficient because according to MSDN

The CompareTo method compares the Ticks property of the current instance and the value, but ignores their Kind . Before mapping DateTime objects, make sure the objects represent time in the same time zone.

Since it compares Ticks from two DateTime instances, so this is an efficient comparison method.



As a side note, if you want to find the interval between DateTime instances, you can use DateTime.Subtraction , it will give TimeSpan

both DateTime instances. So you can find the full difference in minutes, hours, days, seconds, milliseconds using the TimeSpan properties .

DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15);
DateTime dateNow = DateTime.Now;

TimeSpan interval = dateNow.Subtract(date1);

double totalHours= interval.TotalHours;
double totalMinutes = interval.TotalMinutes;
double totalSeconds= interval.TotalSeconds;
double totalMilliseconds= interval.TotalMilliseconds;

      

0


source


In my opinion the method you suggested is the most efficient and acceptable way to compare 2 DateTime

variables in C #, given that you need to take action if the 2 dates are also equal.

Side note :

If you need to compare 2 DateTime

without an equal condition, you can simply write:



if (currentDateTime < eventDateTime)
    Response.Write("is earlier than Do Nothing");
else
    Response.Write("Time is greater, Trigger Action");   

      

which is a little cleaner and more efficient.

+2


source


You can use a nested if else statement like below:

if (currentDateTime < eventDateTime)
   Response.Write("is earlier than Do Nothing");
else if(currentDateTime > eventDateTime)
   Response.Write("time is greater, Trigger Action");   
else
   Response.Write("is the same time as: Do Nothing");

      

0


source







All Articles