如何为.net Core 2.0 WebAPI设置默认日期时间格式 [英] How to set default datetime format for .net core 2.0 webapi

查看:919
本文介绍了如何为.net Core 2.0 WebAPI设置默认日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前在我的本地。该API期望与SQL Server数据库中的yyyy-mm-dd相同。

Currently in my local. The API is expecting the same formart as in SQL Server database which is yyyy-mm-dd.

但是,当我将应用程序部署到生产服务器中时。该API期望日期时间格式为yyyy-dd-mm。

However when i am deploying the application into production server. The API is expecting the datetime format as yyyy-dd-mm.

是否可以将.net核心网络api配置为默认接受yyyy-mm-dd

Is there any way to configure my .net core web api to accept yyyy-mm-dd as default format in every enviroment?

推荐答案

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

这篇关于如何为.net Core 2.0 WebAPI设置默认日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆