3

In my app I've a ticker which runs every 5 seconds. I've also an internal clock and I want to detect when the day chages. To test, I have tried the following code without success:

DateTime A = new DateTime(2019, 6, 20, 23, 58, 29);       
DateTime B = new DateTime(2019, 6, 21, 00, 01, 12);
Int32 dd = (B-A).Days;          // it returns 0
double dd = (B-A).TotalDays;    // it return 0.00002136213 

If I check if TotalDays > 0 I succesfully detect the day change but in the follwing case (with a difference of a minute)

DateTime C = new DateTime(2019, 6, 20, 12, 58, 29);
DateTime D = new DateTime(2019, 6, 20, 12, 59, 29);

the compare fails. Since I need to call a method when day changes, with the example above its called every time and I do not want this behevior. Any hint?

Otto Vasken
  • 67
  • 1
  • 6
  • What do you mean, do you want to know when twenty four hours has passed or simply when the application has been running for a day, then change the value? – Greg Jun 21 '19 at 15:28
  • 2
    The result is correct. You possibly wants to set time of both dates to 00:00:00 and then subtract. Try (B.Date - A.Date).Days – Anil Goel Jun 21 '19 at 15:29
  • Your answer is here(https://stackoverflow.com/questions/8480063/event-for-datechange-at-midnight?lq=1) – Maria Jun 21 '19 at 15:37
  • @AnilGoel I think yours is the best solution, thanks – Otto Vasken Jun 21 '19 at 15:55

3 Answers3

5

compare Date part of DateTime directly

bool isSameDay = (A.Date == B.Date);
ASh
  • 34,632
  • 9
  • 60
  • 82
3

Look at only the Date parts

DateTime A = new DateTime(2019, 6, 20, 23, 58, 29);       
DateTime B = new DateTime(2019, 6, 21, 00, 01, 12);
Int32 dd = (B.Date-A.Date).Days;  
Steve Todd
  • 1,250
  • 6
  • 13
2

For your ticker why not use TimeSpan variables to complete your comparison. You set 1 static timespan variable to 24 hours (1 day) and then create a secondary one to store the values. You then set your second timespan variable equal to the subtraction of your two days and this would let you know if a day had gone by.

`

TimeSpan newDayReference = new TimeSpan(24,0,0);
TimeSpan comparison;

//These two variables set to show difference.
DateTime A= DateTime.Now.AddDays(-1);
DateTime B = DateTime.Now;
comparison = B - A;

if(comparison > newDayReference){ //success }

`

Devon
  • 21
  • 1