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?