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

查看:77
本文介绍了如何为 .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 core web 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.

这种方法有几个原因.

  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天全站免登陆