如何用Noda Time找到昨天的开始和结束?

时间:2015-06-19 00:03:19

标签: c# nodatime

我试图从Noda Time获得昨天的第一个/最后一个毫秒(这可能也适用于其他日期),我想我已经接近但不确定我是否做得对。

如果我可以将昨天转换。在午夜()到Ticks我可以在一天减去1添加滴答数来给我结束时间。这是否有意义,并且根据我的要求,它是Noda Time的最正确用法吗?

谢谢你,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

更新

Noda docs显示Period.Between也可能有用,所以我会测试一下。

1 个答案:

答案 0 :(得分:1)

似乎不应该比这更难:

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;
}