Instead of "overriding" System.DateTime
, wrap it with own class and use it everywhere
public class ApplicationTime
{
private readonly int _offset;
public DateTime Now => System.DateTime.UtcNow.AddHours(offset);
public ApplicationTime(int hoursOffset) => _offset = hoursOffset;
}
Usage
var applicationTime = new ApplicationTime(1);
var delivery = new Delivery
{
CreatedAt = applicationTime.Now
};
Technically is possible to "override" DateTime.Now
.
But I would not suggest to use it in actual application, especially where your friends developers reading and using your code ;)
This can be done if you are using default location for using
directives, which is on top of the file and you are not using full name of the DateTime
type. (not this: System.DateTime.Now
)
using System;
namespace Business
{
public class Dispatching
{
public string Send(string delivery)
{
return $"Delivery '{delivery}' sent at {DateTime.Now:dd-MM-yyyy HH:mm}";
}
}
}
Because using DateTime;
is located outside of namespace, compiler will look for the type DateTime
from Business
namespace first and if not found will check imported namespaces.
So we can take advantage of this and introduce our own implementation of DateTime
inside Business
namespace.
namespace Business
{
public class DateTime
{
public static System.DateTime Now => System.DateTime.UtcNow.AddHours(1);
}
}
Then
var output = new Dispatching.Send("to destination");
Console.WriteLine(output);
// Delivery 'to destination' sent at 01-12-2019 03:10:49
// UTC time + 1 hour
If we put using
directive inside namespace, our "overriding" will be ignored.
namespace Business
{
using System;
public class Dispatching
{
public string Send(string delivery)
{
return $"Delivery '{delivery}' sent at {DateTime.Now:dd-MM-yyyy HH:mm}";
}
}
}