且构网

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

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

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

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.

使用此方法有两个原因。

There's a couple of reasons for this method.


  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;
    }
}