DateTime does not update in Console.WriteLine [closed]

-2

When I click the button, something is written to the Console along with the date, but the time does not update.

Code:

private void button2_Click(object sender, EventArgs e)
    {
            Console.WriteLine("{0}", data.ToString("HH:mm:ss:fff"));
    }

Console: 11: 37: 55: 540 11: 37: 55: 540 11: 37: 55: 540 11: 37: 55: 540

    
asked by anonymous 24.09.2017 / 16:39

3 answers

2

DateTime is not a "clock" that changes its representation over time.

DateTime is immutable, it represents the instant it was created.

To do what you think you have to create a DateTime object whenever you want to display the current instant:

private void button2_Click(object sender, EventArgs e)
{
    Console.WriteLine("{0}", DateTime.Now.ToString("HH:mm:ss:fff"));
}
    
24.09.2017 / 16:54
0

I did not quite understand your question. But from what I understand you need to update the time each time you click the button. So, there's the code

private void button2_Click(object sender, EventArgs e)
{
     var date = DateTime.Now;//Se esta variável já estiver criada, remova o 'var'
     Console.WriteLine("{0}", data.ToString("HH:mm:ss:fff"));
}

And if it is to update the time alone, it uses a timer since it is using WinForms as well.

    
24.09.2017 / 16:52
0

Now you're updating ..

private void button2_Click(object sender, EventArgs e)
        {
            DateTime dt = new DateTime();
            dt = DateTime.Now;
            Console.WriteLine("[{0}]", dt.ToString("HH:mm:ss:fff"));
            }
    
24.09.2017 / 17:08