09 January, 2010

Compare Datetime Objects

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);

Generate 16 Digit Unique Number in CSharp

Now i am going ot discuss about how to Generate 16 digit Unique number
So ,

5 digit Random using System.Random Class

5 digit number by using TimeSpan

6 numbers by System Time (HH:MM:SS)

This is the Code

System.Random fiveRandom = new Random();
TimeSpan tsFive = new TimeSpan();
tsFive = DateTime .Now.Subtract (Convert.ToDateTime ("01/01/1900"));
string rad = fiveRandom.Next(10000, 99999) + tsFive.Days.ToString() + System.DateTime.Now.Hour.ToString ("00") + System.DateTime.Now.Minute.ToString ("00") + System.DateTime.Now.Second.ToString ("00") ;