In this program out is:
04/07/2013 5:19:12 PM
False
But expected output is:
04/07/2013 5:19:12 PM
True
Please correct this program.
using System;
class Program
{
static void Main()
{
DateTime value = DateTime.Now;
Console.WriteLine(value);
Console.WriteLine(value == DateTime.Now);
Console.ReadKey();
}
}
/*
04/07/2013 5:19:12 PM
False
*/
Loading
VulpesPosted Jul 4, 2013, 7:38 PM
using System;
class Program
{
static void Main()
{
DateTime value = DateTime.Now;
Console.WriteLine(value);
Console.WriteLine(value.Date == DateTime.Now.Date);
Console.ReadKey();
}
}
This will always return true unless 'value' is determined slightly before midnight on any given day.
Posted Jul 5, 2013, 6:25 AM
VulpesPosted Jul 5, 2013, 5:03 AM
A 'tick' is one ten millionth of a second which is a small interval of time even by programming standards.
It follows that when you call DateTime.Now at two different points in a running program the 'ticks' value is going to be different and so the 'equals' operator will return false.
To get it to return true, you therefore need to bring the two DateTimes onto a common basis before the values are compared.
The most obvious way of doing this is to compare the 'date' components of the two values (i.e. the Date property) which are going to compare equal except when the first value was take just before midnight.
You could also compare the millisecond, second, minute etc components of the two values though clearly the shorter the interval chosen the more chance there is that the two values will still compare false.
Posted Jul 4, 2013, 7:53 PM
It is highly desirable if you can explain how you determined the code Console.WriteLine(value.Date == DateTime.Now.Date);