Reputation: 41
In a game, I want to trigger an event every night at midnight. The following code is not working:
void Update()
{
var tomorrow = DateTime.Now.AddDays(1).ToShortDateString();
var today = DateTime.Now.ToShortDateString();
if (tomorrow == today)
{
THE THING I WANT TO HAPPEN AT MIDNIGHT;
}
}
In debugging I have found that THE THING I WANT TO HAPPEN works fine. However, the event isn't triggering from the if statement.
I searched the archives for answers, and found some, but the solutions aren't working - this is almost certainly a simple error due to my extremely low-level programming knowledge.
Any assistance would be great...Thanks!
Upvotes: 4
Views: 1011
Reputation: 18125
Your code is effectively asking "1 == 1 + 1
?" and the answer will always be no.
You need to keep the last execution date stored outside the method, and you also need to be more careful how you do your comparison. For instance, DateTime.Now == DateTime.Now
might return false (and pretty often), because DateTime
stores the time down to the tick, and if it's off by even one tick, it won't be considered equal.
Try this:
DateTime lastExecutionDate = DateTime.Utc;
void Update()
{
var tomorrow = DateTime.Now.AddDays(1).ToShortDateString();
var now = DateTime.Utc;
if (lastExecutionDate.Day < now.Day)
{
lastExecutionDate = now;
// this code will be called as close to midnight as unity allows.
}
}
I'm not sure if it will be considered midnight immediately when the game starts. If it is, try using this for lastExecutionDate
instead...
DateTime lastExecutionDate = DateTime.UtcNow + TimeSpan.FromDays(1);
Upvotes: 2
Reputation: 15941
if (tomorrow == today)
this will never be true. If it is exactly midnight (Jan 01 2000 12:00:00.0000
) then this line: tomorrow = DateTime.Now.AddDays(1)
will equal midnight...tomorrow, all the time (Jan 02 2000 12:00:00.0000
). The same applies to every other date-time.
You're better off checking to see if the current time is midnight, then store the current date somewhere and DoTheThing()
only if it's currently midnight and the stored date is not today's date.
Of course, this also ignores the issue of "do you want the event to be triggered retroactively if the application is not actively run at midnight." In which case, TimeSpan
s and Last_run_date
may be of interest.
Upvotes: 0