如何为.net Core 2.0 WebAPI设置默认日期时间格式 [英] How to set default datetime format for .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.
- 这是可测试的。
- 它从您的业务逻辑中提取
DateTime
的依赖关系。 - 如果使用其他系统您的应用中可能需要其他格式,只需创建一个新的
MyAppDateTimeProvider
- It's testable.
- It abstracts the dependency of
DateTime
out of your business logic. - 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屋!