Date format problem (mm/dd/yyyy)

Asked

Viewed 1,535 times

0

I have an ASP.NET Core application and can’t find a solution to my date format problem. My application, is published on a Microsoft Azure server, which is probably in the US (although it appears south of Brazil) and has caused me these disorders.

I have another application on MVC5 that is also published in Azure and that does not give me trouble, I simply defined the culture on the web.config and was solved the date problem.

  <system.web>
    <globalization culture="pt-BR" />
    <compilation debug="true" targetFramework="4.5" />
  </system.web>

In ASP.NET Core, I found a few posts on culture definition in startup.Cs, but I’ve tried a few things without success. Someone’s been through this and you know how I solve my problem?

Something I’ve tried before:

public void ConfigureServices(IServiceCollection services)
        {
            //Setting Culture

            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddMvc().AddViewLocalization().AddDataAnnotationsLocalization();

            //services.AddScoped<LanguageActionFilter>();

            services.Configure<RequestLocalizationOptions>(
               options =>
               {
                   var supportedCultures = new List<CultureInfo>
                       {
                            new CultureInfo("pt-BR")

                       };

                   options.DefaultRequestCulture = new RequestCulture(culture: "pt-BR", uiCulture: "pt-BR");
                   options.SupportedCultures = supportedCultures;
                   options.SupportedUICultures = supportedCultures;
               });

EDITED: I hadn’t made my problem clear... Although I put the above information in the statup.Cs the dates in my Controller is mm/dd/yyyy, that is, I have a calendar in the application, the user chooses the date in the Picker and have it saved with the date 20/08/2017 and the error, but if it fills the date 08/20/2017 works.

In my VIEW:

  @*MODAL REGISTRAR AGENDA*@
    <div class="modal fade" id="ModalAgenda" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg lg-effect-10" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">Registro de Compromisso</h3>
                </div>
                <div class="modal-body">
                    <div class="row no-padding">
                        <div class="col-sm-12" style="padding-left: 0; padding-right: 0;">
                            <div class="panel">
                                <div class="panel-body">
                                    <div class="row">
                                        <div class="form-group col-sm-4">
                                            <label>Tipo</label>
                                            <select class="form-control" name="tipoAgenda" id="tipoAgenda">
                                                <option selected="selected">SELECIONE</option>
                                                <option value="1">CONTATO</option>
                                                <option value="2">VISITA</option>
                                                <option value="3">REUNIAO</option>
                                                <option value="4">TOUR COMERCIAL</option>
                                                <option value="5">APRESENTAÇÃO</option>
                                                <option value="6">ASSEMBLÉIA</option>
                                            </select>
                                        </div>
                                        <div class="form-group col-sm-8">
                                            <label class="control-label">Título</label>
                                            <input class="form-control" name="Titulo" id="Titulo" data-val="true" />
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="form-group col-sm-12">
                                            <label class="control-label">Descrição</label>
                                            <textarea class="form-control" name="Descricao" id="Descricao" data-val="true" rows="6"></textarea>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="form-group  col-sm-4" id="data1">
                                            <label class="control-label">Data</label>
                                            <div class="input-group date">
                                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" name="Data1" id="Data1" class="form-control">
                                            </div>
                                        </div>

                                        <div class="form-group col-sm-2">
                                            <label class="control-label">Hora Início</label>
                                            <div class="input-group clockpicker" data-autoclose="true">
                                                <input type="text" name="HoraInicio" id="HoraInicio" class="form-control">
                                                <span class="input-group-addon">
                                                    <span class="fa fa-clock-o"></span>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="form-group col-sm-2">
                                            <label class="control-label">Hora Fim</label>
                                            <div class="input-group clockpicker" data-autoclose="true">
                                                <input type="text" name="HoraFim" id="HoraFim" class="form-control">
                                                <span class="input-group-addon">
                                                    <span class="fa fa-clock-o"></span>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <br />
                                    <div class="row">
                                        <div class="form-group col-sm-2">
                                            <label class="control-label">Notificar</label>
                                            <input type="text" name="Notifica" id="Notifica" class="form-control" style="text-align:center" value="30" />
                                        </div>

                                        <div class="form-group col-sm-4">
                                            <label class="control-label">Antes do agendamento</label>
                                            <select class="form-control" name="tipoAlerta" id="tipoAlerta">
                                                <option selected="selected" value="1">MINUTOS</option>
                                                <option value="2">HORAS</option>
                                                <option value="3">DIAS</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-danger" data-dismiss="modal">Cancelar</button>
                    <button type="button" class="btn btn-success" onclick="GravaAgenda()">Gravar</button>
                </div>
            </div>
        </div>
    </div>

Mu Js who sends the information to the Controller

function GravaAgenda() {

    var prospect = $("#IdProspect").val();
    var tipoagenda = $('#tipoAgenda option:selected').val();
    var titulo = $("#Titulo").val();
    var descricao = $("#Descricao").val();
    var data1 = $("#Data1").val();
    var horainicio = $("#HoraInicio").val();
    var horafim = $("#HoraFim").val();
    var notifica = $("#Notifica").val();
    var tipoalerta = $('#tipoAlerta option:selected').val();


    //Gravar
    var url = "/Agenda/GravaAgenda";

    $.ajax({
        url: url,
        datatype: "json",
        data: { 'prospect': prospect, 'tipoagenda': tipoagenda, 'titulo': titulo, 'descricao': descricao, 'data1': data1, 'horainicio': horainicio, 'horafim': horafim, 'notifica': notifica, 'tipoalerta': tipoalerta },
        type: "POST",
        success: function (data) {
            swal({ type: "success", title: "Gravado com sucesso!", timer: 2000, showConfirmButton: false });
            window.location.reload();
        }
    });
};

My Controller:

 public async Task GravaAgenda(string prospect, string tipoagenda, string titulo, string descricao, string data1, string horainicio, string horafim, string notifica, string tipoalerta)
        {
            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;

            switch (tipoalerta)
            {
                case "3":
                    minutos = Convert.ToInt32(notifica) * 24 * 60;
                    break;
                case "2":
                    minutos = Convert.ToInt32(notifica) * 24;
                    break;
                case "1":
                    minutos = Convert.ToInt32(notifica);
                    break;
            }
            switch (tipoagenda)
            {
                case "1":
                    tipoAgenda = TipoAgenda.Contato;
                    break;
                case "2":
                    tipoAgenda = TipoAgenda.Visita;
                    break;
                case "3":
                    tipoAgenda = TipoAgenda.Reuniao;
                    break;
                case "4":
                    tipoAgenda = TipoAgenda.Tour;
                    break;
                case "5":
                    tipoAgenda = TipoAgenda.Apresentacao;
                    break;
                case "6":
                    tipoAgenda = TipoAgenda.Assembleia;
                    break;
            }

            var dataInicio = Convert.ToDateTime(data1 + " " + horainicio);
            var dataFim = Convert.ToDateTime(data1 + " " + horafim);
            var dataAlerta = dataInicio.AddMinutes(-minutos);

            await ageData.GravaAgenda(Idprospect, usuario, titulo, descricao, dataInicio, dataFim, dataAlerta, tipoAgenda, empresa);
            await new ProspectLogData().RegitroContato(Idprospect, usuario, "REGISTRO DE AGENDAMENTO DO PROSPECT.", "8");
            RedirectToAction("Index");
        }

My recording layer in the Bank

   public async Task GravaAgenda(int Idprospect, string usuario, string titulo, string descricao, DateTime dataInicio, DateTime dataFim, DateTime dataAlerta, TipoAgenda tipoAgenda, int empresa)
        {
            using (var db = new CRMContext())
            {
                var agenda = new Agenda();
                agenda.IdProspect = Idprospect;
                agenda.IdUsuario = usuario;
                agenda.Titulo = titulo.ToUpper();
                agenda.Descricao = descricao.ToUpper();
                agenda.DataInicio = dataInicio;
                agenda.DataFim = dataFim;
                agenda.DataAlerta = dataAlerta;
                agenda.Criado = DateTime.Now;
                agenda.TipoAgenda = tipoAgenda;
                agenda.IdEmpresa = empresa;
                db.Agenda.Add(agenda);
                await db.SaveChangesAsync();
            }
        }
  • What’s the problem, failed to say so ??? report the problem because, Culture is like that in Aspnetcore!

  • Type: where the problem occurs! and when the problem occurs?

  • Thanks @Virgilio edited the post, the problem is in the transition from View to controller. I have a Picker that is configured correctly for rt-BR, the user chooses the date, for example today 04/09/2017 but when sending to the controller he changes the format and writes to the bank 09/04/2017.

  • Whether you can put View and Controller?

  • 1

    I posted View and Controller. I use this same structure in three different projects MVC5 I think I’m not getting it right with Statup and json config.

  • The concept is wrong, because it does not use the class correctly and another if the fields have data type defined if you should not put string data and yes datetime data, test this.

  • Use for date conversion https://msdn.microsoft.com/pt-br/library/w2sa9yss(v=vs.110). aspx

  • It’s not wrong @Virgilio believe me, I have hundreds of structures like this in my applications. Note that the string pq comes from a JS, and is then converted to Datetime in the Controller. The same was true for my MVC5 applications. However as I am not knowing how to properly configure the culture to en-BR in aspet Core, when converting, the string is being converted to "mm/dd/yyyy". That’s exactly my problem, to define CULTURA "en-BR" in Startup.Cs.

  • 1

    @Rogerioazevedo The Virgilionovic is right, this is completely wrong. It works, but it shouldn’t be done like this.

  • Thanks @LINK Virgil spoke to me on Chat, he suggested that I make a Binding model like Scafolding does. In this case I didn’t use it like this, because it’s a different table being called by a Modal, I’m not sure if I can use Bind the same way because I can’t instantiate 2 models in the same View but I’ll try with certainty. I still need to solve the application culture problem as any convert to datetime will convert to mm/dd/yyyy.

  • @Virgilio, it worked out your suggestion of parseExact using Provider Culture, so far it solves my problem. I will rewrite the controller by doing Binding as you suggested, but since I need the Convert to add String Data + String Time I will continue with the problem despite Binding. I’ll still need someone who knows how to define the culture in Aspnet Core.

  • this is how it defines the Culture, has no other way @Rogerioazevedo and maybe it is server configuration.

  • @Virgilio and LINK thank you very much for your tips, I will consider changing the way I am binding the model. Maybe I have to create a new Viewmodel, since, as I said, the agenda recording is called in a Modal within another Model. If that’s the right way, I’ll learn how to do it! As for the culture problem in aspnet core, I finally found the solution, and I’m going to post here to help other colleagues who need the same thing.

Show 9 more comments

1 answer

2


Finally! I was already going crazy with this problem! With the tip of the colleague @Virgilio I did a workaround and managed to avoid that in the conversion of the string to Datetime, the date left from "dd/mm/yyyy hh:mm:ss" to "mm/dd/yyyy hh:mm:ss" because the project is published in the USA.

Fix Culture in the CONTROLLER

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("pt-BR");            
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);

Fixing the culture in the Controller would solve part of the problem, because I would always have to do the same thing in all Controllers, I needed to fix the culture for the project. And I got it this way.

Aquivo Startp.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 pt-BR
            RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions
            {
                SupportedCultures = new List<CultureInfo> { new CultureInfo("pt-BR") },
                SupportedUICultures = new List<CultureInfo> { new CultureInfo("pt-BR") },
                DefaultRequestCulture = new RequestCulture("pt-BR")
            };
            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();
        }
  • You can mark your own answer as accepted :-)

  • Oops, I forgot, thanks @vnbrs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.