How to find the the start and end of a yesterday with Noda Time?

1.2k views Asked by At

I'm trying to get the the first/last milliseconds from yesterday (which probably applies to other dates too) with Noda Time, and I think I'm close but not sure if I have done this right.

If I could convert yesterday.AtMidnight() to Ticks I could then add the number of ticks in a day minus 1 to give me the end time. Does this make sense and is it the most correct usage of Noda Time given my requirements?

Thank you, Stephen

//Come up with the begin and end parameters in milliseconds for a Oracle query

//Assumption is that this code will run from Midnight to 4AM
//Assumption is this application code will run on servers in the Midwest USA
//Assumption is the database servers are on the West coast USA


Instant now = SystemClock.Instance.Now;
Duration duration = Duration.FromHours(24);
LocalDate yesterday = now.InUtc().Minus(duration).Date;

Console.WriteLine(yesterday.AtMidnight());

// add a day minus one tick

UPDATE

The Noda docs show that Period.Between might be useful too, so I will test that out.

1

There are 1 answers

3
Nicholas Carey On BEST ANSWER

Doesn't seem like it should be any more difficult than this:

public static void DefineYesterday( out LocalDateTime yesterdayStartOfDay , out LocalDateTime yesterdayEndOfDay )
{
  BclDateTimeZone tz         = NodaTime.TimeZones.BclDateTimeZone.ForSystemDefault() ;
  LocalDateTime   now        = SystemClock.Instance.Now.InZone(tz).LocalDateTime ;
  LocalDateTime   startOfDay = now.PlusTicks( - now.TickOfDay ) ;

  yesterdayStartOfDay = startOfDay.PlusDays(  -1 ) ;
  yesterdayEndOfDay   = startOfDay.PlusTicks( -1 ) ;

  return;
}