C # Convert to datetime 00:60:00

3

I have a chronometer with this code:

private void cronometro_Tick(object sender, EventArgs e)
{
    seg++;
    if(seg == 60)
    {
        min++;
        seg = 0;
    }
    else if (min == 60)
    {
        hr++;
        min = 0;
    }
    str_crono = hr.ToString().PadLeft(2, '0') + ":" + min.ToString().PadLeft(2, '0') + ":" + seg.ToString().PadLeft(2, '0');
       label7.Text = str_crono;

}

After this, I try to break down to convert all the time of the chrono to seconds with this code:

DateTime conversionlabel = System.Convert.ToDateTime(str_crono);

int hh = conversionlabel.Hour;
int mm = conversionlabel.Minute;
int ss = conversionlabel.Second;

The drawback is that when str_crono equals: 00:60:00 it sends me this error:

  

The string represents a DateTime not supported in the System.Globalization.GregorianCalendar calendar. **

Any ideas? what am I doing wrong? Thanks !!

    
asked by Jacobo Rodriguez 28.08.2018 в 11:12
source

1 answer

2

There are many ways to implement a stopwatch, but I leave a simple one where time is controlled by a datetime type variable, which is simply added seconds in each tick of the timer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ejemplos
{
    class Crono
    {
        System.Timers.Timer tmr;
        DateTime tiempo;

        public Crono()
        {
            tmr = new System.Timers.Timer();
            tmr.Interval = 1000; // Se ejecutará una vez por segundo.
            tmr.Elapsed += Tmr_Elapsed;

        }

        public void Iniciar()
        {
            tmr.Start();
            tiempo = new DateTime(1900, 1, 1, 0, 0, 0);
        }

        private void Tmr_Elapsed(object sender,     System.Timers.ElapsedEventArgs e)
        {
        tiempo = tiempo.AddSeconds(1);

        Console.WriteLine("{0}:{1}:{2}",
                         tiempo.Hour.ToString().PadLeft(2, '0'),
                         tiempo.Minute.ToString().PadLeft(2, '0'),
                         tiempo.Second.ToString().PadLeft(2, '0'));
        }

        static void Main()
        {
            Crono c = new Crono();
            c.Iniciar();
            Console.WriteLine("Presiona una tecla para finalizar");
            Console.ReadKey();

        }

    }
}
    
answered by 29.08.2018 / 21:58
source