Convert data c#

Asked

Viewed 899 times

5

Good people I’m having a problem with my code. I in my database have a field like date Only that after calling him to the program he also passes me the time , is something of the genre: 18-03-2015 00:00:00. What I wanted was just part of the date and before I came here I tried this

DateTime data = Convert.ToDateTime(reader["DATA"]);
                DateTime dataOnly = data.Date;
                string dataFinal = dataOnly.ToString("d");
                Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyy"));

And this did exactly what I wanted but in the program I have to do it just inserts the last date. I’ll leave the code down here and an image for you to understand better

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace experiencia
{
    class Program
    {
        static void Main(string[] args)
        {

            SageNGCOApi.BaseNext SageNextAPI = new SageNGCOApi.BaseNext();
            SageNextAPI.PercIni = "C:\\ProgramData\\Sage\\2070\\Next\\";
            SageNextAPI.PercLOG = "C:\\ProgramData\\Sage\\2070\\Next\\";
            SageNextAPI.Empresa = "FDISQL";
            SageNextAPI.Password = "teste";
            SageNextAPI.Login = "teste";
            int resultado;
            resultado = SageNextAPI.Iniciar();
            if (resultado != 0) // 0: Sucesso
            {
                Console.WriteLine("Erro ao iniciar Sage Next API");
            }
            else
            {
                Console.WriteLine("SUCESSO!");
            }

            string text = System.IO.File.ReadAllText(@"C:\Users\Hugo\Desktop\teste\config.ini");
            SqlConnection conn = new SqlConnection(text);
            conn.Open();
            var cmd = new SqlCommand(@"SELECT * from my_cab", conn);
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                SageNGCOApi.DocumentoComercial documento = new SageNGCOApi.DocumentoComercial();
                documento.ActivarGrelhasDesconto = false;
                documento.ActivarLinhasBonus = true;
                documento.ActivarLinhasPreco = true;


                DateTime data = Convert.ToDateTime(reader["DATA"]);
                DateTime dataOnly = data.Date;
                string dataFinal = dataOnly.ToString("d");
                Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyy"));




                documento.cab.Sector = Convert.ToString(reader["SETOR"]);
                documento.cab.TipoDocumento = Convert.ToString(reader["DOCUMENTO"]);
                documento.cab.Serie = 1;
                documento.cab.Data = DateTime.Now.ToString("dd-MM-yyyy");
                documento.cab.NossoNoDocumento = 0; // 0 lê numerador
                documento.cab.Terceiro = Convert.ToString(reader["TERCEIRO"]);
                documento.cab.Moeda = "EUR";
                documento.cab.RegimeIva = documento.Cliente.REGIVA;
                documento.Origem = SageNGCOApi.eOrigemDocumento.NaoAplicavel;



                SqlCommand cmd_1 = new SqlCommand("SELECT * FROM MY_LIN WHERE REGISTO=@reg", conn);
                cmd_1.Parameters.AddWithValue("@reg", reader["REGISTO"]);
                SqlDataReader le = cmd_1.ExecuteReader();

                while (le.Read())
                {

                    SageNGCOApi.DocumentosGcLin linha = new SageNGCOApi.DocumentosGcLin();

                    linha.TipoDeLinha = 1; // 1-Movimento; 2-Abatimento; 3-Despesa; 4-Informativo
                    linha.Armazem = Convert.ToString(le["ARMAZEM"]);
                    linha.Artigo = Convert.ToString(le["ARTIGO"]);
                    linha.Unidade = Convert.ToString(le["UNIDADE"]);
                    linha.PrecoUnitario = Convert.ToDecimal(le["PRECO"]);
                    linha.Valor = Convert.ToDecimal(le["VALOR"]);
                    linha.Quantidade = Convert.ToDecimal(le["QNT"]);
                    linha.Desconto = Convert.ToString(le["DESCONTO"]);
                    linha.TaxaDesconto = Convert.ToDecimal(le["T_DESC"]);
                    documento.SugereValoresLin(linha, false, true, true, false, false, false, true);
                    documento.AdicionaLinha(linha);
                }


               if (documento.Validar() == 0)
                {
                    if (documento.Inserir() == 0)
                        if (resultado == 0) // 0: Sucesso
                        {
                            Console.WriteLine("Documento inserido com sucesso!");
                        }
                        else
                        {
                            Console.WriteLine("Erro ao inserir documento: " + documento.UltimaMensagem());
                        }
                }
               else
               {
                   Console.WriteLine("Erro ao validar documento: " + documento.UltimaMensagem());
               }
            }
            Console.ReadLine();
        }
    }
}

If I use the date as the current date DateTime.Now.ToString("dd-MM-yyyy") it works and inserts all the dates however if I use the date as the date that comes from the database and then convert it just inserts the last one. I leave some images to understand better and if you know I would appreciate it if you help me. Thanks!

Data Atual

Data que vem da base de dados convertida

  • Looking at this code I could not find the problem. See http://answall.com/help/mcve

  • Ever tried a debug?

  • Yeah, I don’t know what the problem is and I’ve spent hours on it trying to find a solution. What is a debug? I’m sorry but I don’t know much about c#

  • I don’t see where you use the variable dataOnly and/or dataFinal, for here: documento.cab.Data = DateTime.Now.ToString("dd-MM-yyyy"); is using the current time. Is it because it is the program that is being shown first? When nay it works, that’s when you have something like this: document.cab.Data = dataFinal;?

  • And the function documento.Inserir(), is very complex? Consider creating a Gist if necessary.

  • After all, what are you trying to do? Explain in a nutshell, your question is very complex and barely readable. Be clearer.

  • It would not be better to use Dataset instead of Datareader?

  • Learn here how to debug: https://www.youtube.com/watch?v=6zoIzC_nmxs

Show 3 more comments

3 answers

3

Simply write

NomeVariavel.ToShortDateString();

There is no reason to make it difficult when there are native features for these situations.

1

You can use the Tryparseexact() to do this your code would look like this.

DateTime valor;
DateTime.TryParseExact(reader["DATA"], "dd/MM/yyyy",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out valor);

    ....
    documento.cab.Serie = 1;
    documento.cab.Data = valor;

    ....

1

If what you want is just to print the date on the screen, try it like this:

Console.WriteLine(Convert.ToDateTime(reader["DATA"]).ToString("dd-MM-yyyy"));

This way you show the date value that came from the BD without the time.

  • But the problem is not to show without the part of the time that I already managed to do the problem is that if I do the conversion after the program does not work properly as you can see in the 2 images above the console, and that’s what I do not understand why it gives error.

  • @Hugo, good morning. I don’t understand your explanation. From what I see in the two exits, when you use Now, it repeats and that’s what you don’t want, right? When you don’t use Now then it prints the correct dates from your bank. That’s what I’m seeing in the exits you posted in the initial post. Which error the application generates?

  • @Hugo, hello reading now with more details understood. What I commented, read the opposite. The problem may be in your methods Insert() and Validate(). Take a look at it in detail or post here to make a better analysis.

Browser other questions tagged

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