How to set default datetime format for .net core 2.0 webapi

血红的双手。 提交于 2019-12-22 11:24:58

问题


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

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

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


回答1:


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



回答2:


Please show some code. You can try the following in the AddJsonOpions() pipeline in ConfigureServices()

services
        .AddMvc()
        .AddJsonOptions(options =>
                        {
      //Set date configurations
      //options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd"; // month must be capital. otherwise it gives minutes.
                        });


来源:https://stackoverflow.com/questions/49976468/how-to-set-default-datetime-format-for-net-core-2-0-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!