Compare Datetime Objects

Posted by Venkat | Labels: ,

Here i am going to share
1) How to Compare two Datetime object ( here i am mentioning some ways to Compare Datetime Variables )
2) How to get the timeSpan Values from the Hours and add hours to the Datetime its easy.

It can be expressed as a date and time of day.

It compares Date with time.

DateTime chkExpireDateTime = new DateTime(2009, 8, 1, 0, 0, 0);

if (DateTime.Compare(DateTime.Now , chkExpireDateTime)< 0)
{
// the Current Datetime.now is less than ChkExpireDateTime
}
else if (DateTime.Compare(DateTime.Now, chkExpireDateTime) > 0)
{
// the Current Datetime.now is Greater than ChkExpireDateTime
}
else if (DateTime.Compare(DateTime.Now, DateTime.Now) == 0)
{
// the Current Datetime.now and ChkExpireDateTime are Equal
}

You can also Compare this way.

DateTime systemDate = DateTime.Now;
DateTime compareDate = DateTime.Today.AddHours(11D);

// less than
if (compareDate < systemDate)
Console.WriteLine("Less Than");

// equal to
if (compareDate == systemDate)
Console.WriteLine("Equal To");

// greater than
if (compareDate > systemDate)
Console.WriteLine("Greater Than");

// basically you can compare it in all the normal ways
// using !=, ==, , =, etc



The below code is used to get the Timespan for the for the hours and minutes given through the string.

string time = "02:10";
string[] pieces = time.Split(new char[] { '.' },

StringSplitOptions.RemoveEmptyEntries);
TimeSpan difference2 = new TimeSpan(Convert.ToInt32(pieces[0]),

Convert.ToInt32(pieces[1]), 0);
double minutes2 = difference2.TotalMinutes; // 130
double totalSeconds = difference2.TotalSeconds; // 7800

// this will add the seconds to the Datetime

DateTime getOutTime = new DateTime();
getOutTime = DateTime.Now.AddHours(Convert.ToDouble (getHours ));
getOutTime = DateTime.Now.AddSeconds(totalSeconds);

PayOffers.in