mokh223
mokh223

Reputation: 624

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

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?

Upvotes: 4

Views: 19108

Answers (2)

Felix Too
Felix Too

Reputation: 11931

Please show some code. You can try the following in the AddJsonOptions() 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.
                        });

Upvotes: 18

Adam Vincent
Adam Vincent

Reputation: 3821

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

Upvotes: 2

Related Questions