I have my following codes as below. It works in most scenario but today I one scenario where the expiration_date
is 09/30/2017 00:00:00
is less than currentDateTime
which is in string
as 10/15/2016 14:34:19
? What is the bug on my side I just comparing as string
?
System.DateTime expiration_date = newVer.License.Status.Expiration_Date;
DateTime currentDateTime = DateTime.Now;
currentDateTime.ToString("MM/dd/yyyy HH:mm:ss");
int a = expiration_date.ToString("MM/dd/yyyy HH:mm:ss")
.CompareTo(currentDateTime.ToString("MM/dd/yyyy HH:mm:ss"));
//MessageBox.Show("int a is :" + a);
if (expiration_date.ToString("MM/dd/yyyy HH:mm:ss")
.CompareTo(currentDateTime.ToString("MM/dd/yyyy HH:mm:ss")) < 1)
{
crossDate = 1;
MessageBox.Show("Cross Date Alert"+ " Expiry Date Is :"+
expiration_date.ToString("MM/dd/yyyy HH:mm:ss")
+ " "+"Current Date Is :"+
currentDateTime.ToString("MM/dd/yyyy HH:mm:ss"));
}
Compare datetime as you would compare numbers such as
DateTime expiration_date = newVer.License.Status.Expiration_Date;
DateTime currentDateTime = DateTime.Now;
if( expiration_date < currentDateTime)
{
// expired
}
If you need only date and not time then use
DateTime expiration_date = newVer.License.Status.Expiration_Date.Date;
DateTime currentDateTime = DateTime.Now.Date;
You can also use day difference of two date.
int daydiff = (int)((currentDateTime - expiration_date).TotalDays)
Your question has a two-part answer. There may be something easier, but:
First, convert your string to a DateTime object. The DateTime class has several methods to help with this. Try ParseExact.
Then, convert the DateTime object to a Unix timestamp.
Now, you have two long ints, that you can compare, and convert the int comparison to another DateTime, and take things from there.
Compare dates example:
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(1);
if ( d2.CompareTo(d1)>0 )
Console.WriteLine("d2>d1");
else
Console.WriteLine("d2<=d1");
don't convert to strings
DateTime expiration_date = newVer.License.Status.Expiration_Date;
if (expiration_date.CompareTo(DateTime.Now) < 1)
{
MessageBox.Show("Cross Date Alert"+ " Expiry Date Is :"+ expiration_date.ToString("MM/dd/yyyy HH:mm:ss") + " "+"Current Date Is :"+ currentDateTime.ToString("MM/dd/yyyy HH:mm:ss"));
}
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