Instant.Now for NodaTime

前端 未结 2 1821
南旧
南旧 2021-02-03 20:03

I\'m trying to get a handle on using the Noda Time framework by Jon Skeet (and others).

I\'m trying to store the current now(Instant). Instant is created from a long t

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-03 20:55

    SystemClock.Now returns the current time as an Instant value:

    Instant now = SystemClock.Instance.Now;
    

    But you may want to heed the remarks in the documentation for the IClock interface:

    IClock is intended for use anywhere you need to have access to the current time. Although it's not strictly incorrect to call SystemClock.Instance.Now directly, in the same way as you might call UtcNow, it's strongly discouraged as a matter of style for production code. We recommend providing an instance of IClock to anything that needs it, which allows you to write tests using the stub clock in the NodaTime.Testing assembly (or your own implementation).

    As a simple example, suppose you have a Logger class that needs the current time. Instead of accessing SystemClock directly, use an IClock instance that's supplied via its constructor:

    public class Logger
    {
        private readonly IClock clock;
    
        public Logger(IClock clock)
        {
            this.clock = clock;
        }
    
        public void Log(string message)
        {
            Instant timestamp = this.clock.Now;
            // Now log the message with the timestamp... 
        }
    }
    

    When you instantiate a Logger in your production code, you can give it SystemClock.Instance. But in a unit test for the Logger class, you can give it a FakeClock.

提交回复
热议问题