Change default format for DateTime parsing in ASP.NET Core

前端 未结 10 1029
情话喂你
情话喂你 2021-02-02 08:57

I get a Date in an ASP.NET Core Controller like this:

public class MyController:Controller{
    public IActionResult Test(DateTime date) {

    }
}
相关标签:
10条回答
  • 2021-02-02 09:54

    Try setting the culture manually in your web.config

    <configuration>
       <system.web>    
          <globalization culture="de-DE" uiCulture="de-DE"/>
       </system.web>
    </configuration>
    

    EDIT: Since i just realized this is Core, you can do it this way in StartUp.Configure:

    var cultureInfo = new CultureInfo("de-DE");
    CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
    CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
    
    0 讨论(0)
  • 2021-02-02 09:58

    If you don't mind using the generic StatusCode method to make this call, you can do something like the following:

    internal IActionResult CreateResponse(int code, object content = null)
        {
            Type t = content?.GetType();
            bool textContent = t == typeof(string) || t == typeof(bool);
            //
            JsonSerializerSettings dateFormatSettings = new JsonSerializerSettings
            {
    
                DateFormatString = myDateFormat
            };
    
            string bodyContent = content == null || string.IsNullOrWhiteSpace(content + "")
                        ? null
                        : textContent
                            ? content + ""
                            : JsonConvert.SerializeObject(content, dateFormatSettings);
    
            ObjectResult or = base.StatusCode(code, bodyContent);
            string mediaType = 
                        !textContent
                            ? "application/json"
                            : "text/plain";
            or.ContentTypes.Add(new MediaTypeHeaderValue(mediaType));
            return or;
        }
    

    You can add this to a base class and call it like:

    return base.CreateResponse(StatusCodes.Status200OK, new { name = "My Name", age = 23});
    

    It's up to you if you want to create your own Ok, BadRequest, etc...methods, but for me this works and I hope it helps anybody else. You could even default int code = 200, if most of your requests are GETs. This code assumes you either want to respond with a string, boolean, or a custom object, but you can easily handle all primitives by checking Type.GetTypeInfo().IsPrimitive and even doing some checks for decimal, string, DateTime, TimeSpan, DateTimeOffset, or Guid.

    0 讨论(0)
  • 2021-02-02 09:58

    I had same problem ad almost got mad. I tried everthing with no sucsses. First I found a workaround to solve part of my problem:

    Workaround:

    string data1 
    string horainicio 
    string horafim
    
    var ageData = new AgendaData();
    var user = await _userManager.GetUserAsync(User);
    string usuario = user.Id;
    int empresa = user.IdEmpresa;
    int Idprospect = Convert.ToInt32(prospect);
    int minutos = 0;           
    var tipoAgenda = TipoAgenda.Contato;
    
    var provider = CultureInfo.InvariantCulture;
    provider = new CultureInfo("en-US");            
    string formato = "dd/MM/yyyy HH:mm";
    
    var dataInicio = DateTime.ParseExact(data1 + " " + horainicio, formato, provider);
    var dataFim = DateTime.ParseExact(data1 + " " + horafim, formato, provider);           
    var dataAlerta = dataInicio.AddMinutes(-minutos);
    

    But, this way i aways have to set invariantculture to all my datetime. I found the solution setting my culture at the configure on startup.cs.

    Set Culture on startup.cs

     public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, CRMContext context)
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
    
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseDatabaseErrorPage();
                    app.UseBrowserLink();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                //Fixar Cultura para en-US
                RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions
                {
                    SupportedCultures = new List<CultureInfo> { new CultureInfo("en-US") },
                    SupportedUICultures = new List<CultureInfo> { new CultureInfo("en-US") },
                    DefaultRequestCulture = new RequestCulture("en-US")
                };
    
                app.UseRequestLocalization(localizationOptions);      
                app.UseStaticFiles();
                app.UseIdentity();
    
                // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
    
                context.Database.EnsureCreated();
            }
    

    Hope this help you.

    0 讨论(0)
  • 2021-02-02 10:00

    I wanted to format the dates in my responses and I did the following in ConfigureServices method:

    services.AddMvc()
    .AddJsonOptions(options =>
    {
        options.SerializerSettings.DateFormatString = "mm/dd/yy, ffffdd";
    });
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题