2

I writing unit tests for project and in code is a lot references to DateTime.Now. It's bad practice right? Because hosting can be in different time zone as developing.

So I trying to make a useful TimeProvider to using in dayily coding and what can be mocked.

I have made that:

 interface ITimePrivder
    {
        DateTime Now { get; }
        DateTime UtcNow { get; }
        string TimeZone { get; }
    }
    class TimeProvider : ITimePrivder
    {
        public virtual DateTime Now => DateTime.Now;
        public virtual DateTime UtcNow => DateTime.UtcNow;
        public virtual string TimeZone
        {
            get
            {
                lock(this._object)
                {
                int difference = DateTime.Now.Hour - DateTime.UtcNow.Hour;
                string timeZone = (difference >= 0) ? $"+{difference}" : $"-{difference}";
                return timeZone;
            }
            } 
        }
        private object _object = new object();

    }

What do you think? It's useful? Can I using it in my ASP.NET MVC and Console projects safety?

Is now theard safe?

Nerf
  • 938
  • 1
  • 13
  • 30

2 Answers2

2

It depends on how you are using DateTime.Now, but if business logic depends on it and you want to unit test this logic you solution is quite good.

Some other thought oh this matter here and here

Community
  • 1
  • 1
Pavel Krymets
  • 6,253
  • 1
  • 22
  • 35
0

One good strategy is to use one timezone throughout the application, for example GMT. Here you can find more information about datetime provider : Unit Testing: DateTime.Now

Community
  • 1
  • 1
Fabjan
  • 13,506
  • 4
  • 25
  • 52