1

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.

5
  • Can't you just use now and subtract 1 millisecond to get the end time?
    – DavidG
    Jun 19, 2015 at 0:06
  • Ah, good catch @DavidG, I should remove those comments as the job might not start at Midnight, say from 1AM to 6AM. Jun 19, 2015 at 0:16
  • Not really sure what you are after now. Do you just want to determine if a time occurs in a certain range?
    – DavidG
    Jun 19, 2015 at 0:18
  • @DavidG I want to make sure that if a process kicks off, at midnight or later (new day) that it will find yesterdays beginning and ending timestamps correctly. Jun 19, 2015 at 0:34
  • 1
    Marking as a duplicate because everything worth discussing is already in that answer. The only difference is that the dup talks about "today" and you asked for "yesterday", so just subtract one day from the today variables in the methods in the dup answer. Jun 19, 2015 at 3:21

1 Answer 1

1

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;
}
3
  • 2
    Actually, this will be wrong in certain cases, because not every local day starts and ends at midnight. Several time zones have DST transitions that make the day start at 01:00 or end at 23:00. Jun 19, 2015 at 3:19
  • @MattJohnson Does the dupe question you answered cover this scenario? Jun 19, 2015 at 5:21
  • 2
    Yes, by using DateTimeZone.AtStartOfDay, it takes that into account. Jun 19, 2015 at 6:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.