且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为 .net core 2.0 webapi 设置默认日期时间格式

更新时间:2023-02-16 10:14:54

100% 的时间,如果我使用 DateTime,我会为它创建一个接口.当需要进行测试时,它只会让生活变得更轻松.我相信这也适用于您.

100% of the time, If I am using DateTime, I create an interface for it. It just makes life a lot easier when it's time for testing. I believe this would work for you as well.

这种方法有几个原因.

  1. 它是可测试的.
  2. 它将DateTime 的依赖从您的业务逻辑中抽象出来.
  3. 如果您应用中的其他系统可能需要不同的格式,只需创建一个新的 MyAppDateTimeProvider
  1. It's testable.
  2. It abstracts the dependency of DateTime out of your business logic.
  3. If other systems in your app may need a different format, just create a new MyAppDateTimeProvider

public interface IDateTimeProvider
{
    DateTime Now { get; }
    string GetDateString(int year, int month, int day);
    DateTime TryParse(string sqlDateString);
}

public class SqlDateTimeProvider : IDateTimeProvider
{
    public DateTime Now => DateTime.UtcNow;

    public string GetDateString(int year, int month, int day)
    {
        return new DateTime(year, month, day).ToString("yyyy-MM-dd");
    }

    public DateTime TryParse(string sqlDateString)
    {
        var result = new DateTime();
        DateTime.TryParse(sqlDateString, out result);
        return result;
    }
}