Leave date only on the datatime, without the hours part

Asked

Viewed 92 times

3

Hello, I have a project that calls a WebApi which brings the data from the database, but one of the fields in the database is of the type DateTime and in my project, I declared as String (I can change, no problem), what I want is the following: I wanted that when it brings this value, it takes the part of horas and just let the data

The field is: Cba_dt_abertura

How can I do a conversion, or maybe take that part, follows images:

How are you:

inserir a descrição da imagem aqui

As it should be:

inserir a descrição da imagem aqui

My project:

 public async Task<IActionResult> Index()
    {
        Uri BaseAdress = Services.Token.BaseAdress;
        string strToken = Services.Token.strToken;
        List<ContaBancariaModel> ListaContaBancaria;
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.BaseAddress = BaseAdress;
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", strToken);
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("Application/Json"));
            using (HttpResponseMessage response = await httpClient.GetAsync("/api/ContaBancaria/findAll"))
            {

                response.EnsureSuccessStatusCode();
                string resul = await response.Content.ReadAsStringAsync();
                ListaContaBancaria = JsonConvert.DeserializeObject<List<ContaBancariaModel>>(resul);
            }
        }
        return View(ListaContaBancaria);
    }

Method in the Webapi:

[HttpGet]
    [Route("findAll")]
    public HttpResponseMessage findAll()
    {
        try
        {
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            var bancos = bdprincipalEntities.Contas_Bancarias.Select(
                    x => new {
                        Cba_codigo = x.Cba_codigo,
                        Cba_numero = x.Cba_numero,
                        Cba_tipo_conta = x.Cba_tipo_conta,
                        Cba_dt_abertura = x.Cba_dt_abertura,
                        Cba_gerente = x.Cba_gerente,
                        Emp_codigo = x.Emp_codigo,
                        Cba_situacao = x.Cba_situacao.Equals("A") ? "ATIVO" : "DESATIVADO"                           
                    }).ToList();
            result.Content = new StringContent(JsonConvert.SerializeObject(bancos));
            result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            return result;
        }
        catch (Exception)
        {
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        }
    }

3 answers

4


Change the type of the Cba_dt_string open object to Datetime, then when the list is popular put the code below.

    try
    {
        var result = new HttpResponseMessage(HttpStatusCode.OK);
        var bancos = bdprincipalEntities.Contas_Bancarias.Select(
                x => new {
                    Cba_codigo = x.Cba_codigo,
                    Cba_numero = x.Cba_numero,
                    Cba_tipo_conta = x.Cba_tipo_conta,
                    Cba_dt_abertura = x.Cba_dt_abertura.ToShortDateString(), //Coloque esse método
                    Cba_gerente = x.Cba_gerente,
                    Emp_codigo = x.Emp_codigo,
                    Cba_situacao = x.Cba_situacao.Equals("A") ? "ATIVO" : "DESATIVADO"                           
                }).ToList();
        result.Content = new StringContent(JsonConvert.SerializeObject(bancos));
        result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        return result;
    }
  • I don’t know if you tested it, but the visual studio says that Datetime does not contain a definition for 'Toshortdatestring'

  • When I add the stitch I can only use the following methods: "Equals, Gethashcode, Gettype, Getvalueordefault and Tostring".

  • Method documentation: https://docs.microsoft.com/pt-br/dotnet/api/system.datetime.toshortdatestring?view=netframework-4.7.2

  • 2

    John’s answer is correct, but it is important to note that the Toshortdatestring() method is applied to properties of the Datetime type. Jeff could not find the method probably because his Cba_dt_aperture property is of the string type. Jeff, as you reported, you can change the type of your property. Modify().

  • As @Sérgiolopes said, the method is only available for the Datetime type

  • Oh yes, I did not know that, thank you for your reply

  • {"LINQ to Entities does not recognize the method 'System.String Toshortdatestring()' method, and this method cannot be Translated into a store Expression." } I get this error when using this method

  • You switched the attribute x.Cba_dt_aperture to Datetime in your Entity? because the error says that it is trying to use the method in a string.

  • The attribute Cba_dt_entity opening needs to be Datetime, since the Cba_dt_model opening has to be string.

  • I made the changes you said, but gave me error again, but I found a solution, your method is right, must be some error here, thanks for the help, I will post the solution I found

Show 5 more comments

1

Cba_dt_abertura = DateTime.Parse(x.Cba_dt_abertura.ToString()).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),
  • Well, I can’t use the "parse," but I did something similar that I found

0

I found an alternative solution on the internet:

                var bancos = bdprincipalEntities.Contas_Bancarias.Select(
                    x => new {
                        Cba_codigo = x.Cba_codigo,
                        Cba_numero = x.Cba_numero,
                        Cba_tipo_conta = x.Cba_tipo_conta,
                        Cba_dt_abertura = x.Cba_dt_abertura,
                        Cba_gerente = x.Cba_gerente,
                        Emp_codigo = x.Emp_codigo,
                        Cba_situacao = x.Cba_situacao.Equals("A") ? "ATIVO" : "DESATIVADO"                           
                    }).ToList().Select(x => new
                    {
                        Cba_codigo = x.Cba_codigo,
                        Cba_numero = x.Cba_numero,
                        Cba_tipo_conta = x.Cba_tipo_conta,
                        Cba_dt_abertura = string.Format("{0:dd-MM-yyyy}", x.Cba_dt_abertura),
                        Cba_gerente = x.Cba_gerente,
                        Emp_codigo = x.Emp_codigo,
                        Cba_situacao = x.Cba_situacao
                    });

Browser other questions tagged

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