HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Getting the miliseconds from now to the next midday

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
themiddaygettingnextmilisecondsnowfrom

Problem

I need to get the total milliseconds to the next mid-day (12:00:00) to signal a timer that will run once a day.

Assuming the application can be shut down and started anytime, is this code to get the milliseconds left to midday (used to set the timer) correct? (It doesn't need to be exact; it can be off by a few seconds.)

TimeSpan now = DateTime.Now.TimeOfDay;
TimeSpan target = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 0, 0).TimeOfDay;

double r = target.TotalMilliseconds - now.TotalMilliseconds;

if (r > 0) // It's before noon
    ;
else // It's after noon
    r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;

t = new Timer(DoWork, null, r, TimeSpan.FromTicks(TimeSpan.TicksPerDay));


Can it be done more efficiently or in fewer lines of code?

Solution

if (r > 0) // It's before noon
   ;
else // It's after noon
   r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;


Change to:

if (r <= 0) // It's after noon
   r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;


No need to have an if that does nothing.

Code Snippets

if (r > 0) // It's before noon
   ;
else // It's after noon
   r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;
if (r <= 0) // It's after noon
   r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;

Context

StackExchange Code Review Q#1959, answer score: 8

Revisions (0)

No revisions yet.