Cronometro (como somar intervalos de tempo)
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;
namespace WindowsFormsApplication2{ public partial class Form1 : Form { int contUm = 0, contDois = 0; int hor, min, seg; private static TimeSpan tempoTotal = new TimeSpan(); public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) {
}
private void iniciar(object sender, EventArgs e) { contDois++; if (contDois % 2 == 1) { tempo.Start(); btnIniciar.Text = "Pausar";
} else { tempo.Dispose(); btnIniciar.Text = "Iniciar";
} }
private void parar(object sender, EventArgs e) { tempo.Stop(); contUm = 0; contDois = 0; lblTempo.Text = contUm.ToString() + "0:00:00"; btnIniciar.Text = "Iniciar"; txtTempo.Text = string.Format("{0:#,0#}:{1:#,0#}:{2:#,0#}", hor, min, seg); TimeSpan t = new TimeSpan(); t = TimeSpan.Parse(txtTempo.Text); tempoTotal = TimeSpan.Parse(txtTempo.Text); txtTempo.Text = Convert.ToString(t + tempoTotal); }
private void temp(object sender, EventArgs e) { contUm++; hor = (contUm / 3600); min = (contUm % 3600) / 60; seg = (contUm % 3600) % 60; lblTempo.Text = string.Format("{0:#,0#}:{1:#,0#}:{2:#,0#}", hor, min, seg); }
}}
namespace WindowsFormsApplication2{ public partial class Form1 : Form { int contUm = 0, contDois = 0; int hor, min, seg; private static TimeSpan tempoTotal = new TimeSpan(); public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) {
}
private void iniciar(object sender, EventArgs e) { contDois++; if (contDois % 2 == 1) { tempo.Start(); btnIniciar.Text = "Pausar";
} else { tempo.Dispose(); btnIniciar.Text = "Iniciar";
} }
private void parar(object sender, EventArgs e) { tempo.Stop(); contUm = 0; contDois = 0; lblTempo.Text = contUm.ToString() + "0:00:00"; btnIniciar.Text = "Iniciar"; txtTempo.Text = string.Format("{0:#,0#}:{1:#,0#}:{2:#,0#}", hor, min, seg); TimeSpan t = new TimeSpan(); t = TimeSpan.Parse(txtTempo.Text); tempoTotal = TimeSpan.Parse(txtTempo.Text); txtTempo.Text = Convert.ToString(t + tempoTotal); }
private void temp(object sender, EventArgs e) { contUm++; hor = (contUm / 3600); min = (contUm % 3600) / 60; seg = (contUm % 3600) % 60; lblTempo.Text = string.Format("{0:#,0#}:{1:#,0#}:{2:#,0#}", hor, min, seg); }
}}
Vinicius Biá
Curtidas 0
Respostas
Vinicius Biá
19/05/2013
Estou com problemas nesse código, pois quero fazer com que ele a cada parada do cronometro me jogue uma soma de tempo entre os intervalos.
GOSTEI 0
Pjava
19/05/2013
Não sei se entendi bem, mas você poderia jogar em uma variável, o momento inicial. E quando você stopar o cronômetro, você então pegaria esse tempo e subtrairia da variável que tem o tempo inicial. Aí você teria esse intervalo, entre o início e o final.
GOSTEI 0
Vinicius Biá
19/05/2013
mais ou menos assim ?
{
DateTime t_inicio;
DateTime t_fim;
TimeSpan t_diferenca;
if (btnMedir.Text == "Iniciar" )
{
lblDiferenca.Text = "";
t_inicio = DateTime.Now;
btnMedir.Text = "Parar";
}
else
{
t_fim = DateTime.Now;
t_diferenca = t_fim.Subtract(t_inicio);
lblDiferenca.Text = t_diferenca.TotalSeconds.ToString("0.000000") + " segundos";
btnMedir.Text = "Iniciar";
}
}
{
DateTime t_inicio;
DateTime t_fim;
TimeSpan t_diferenca;
if (btnMedir.Text == "Iniciar" )
{
lblDiferenca.Text = "";
t_inicio = DateTime.Now;
btnMedir.Text = "Parar";
}
else
{
t_fim = DateTime.Now;
t_diferenca = t_fim.Subtract(t_inicio);
lblDiferenca.Text = t_diferenca.TotalSeconds.ToString("0.000000") + " segundos";
btnMedir.Text = "Iniciar";
}
}
GOSTEI 0
Vinicius Biá
19/05/2013
Mas eu acho que não deveria usar DateTimer
GOSTEI 0
Pjava
19/05/2013
Sem DateTime, ficará difícil fazer conta. Seria bem mais complicado. Eu colocaria DateTime sim. É mais ou menos sim, o que você postou, apesar de não olhar minuciosamente o seu código.
GOSTEI 0
Vinicius Biá
19/05/2013
Então, é assim: tenho um cronometro no qual o usuário ao clicar no botão Inicio dará start no tempo, então começa a rodar o tempo, e quando o usuário clicar no botão parar, o mesmo me joga o tempo finalizado em uma TexBox, quando o entrar novamente e der start, e apos parar de novo, ai o sistema pega e soma o tempo dado antes com o tempo dado apos e me retorna um tempo total, estou quebrando a cabeça aqui rsrsrs
GOSTEI 0
Pjava
19/05/2013
Você pode ter algo do tipo assim:
DateTime _horaInicio = DateTime.Now;
DateTime _horaFim = Seu_Tempo_Decorrido;
Aí joga num textbox o seguinte:
TimeSpan resultado = _horaFim.Subtract(_horaInicio);
Você então terá sempre a var resultado com o resultado guardado. Depois é só indo acrescentando:
resultado += _horaFim.Subtract(_horaInicio);
Não testei, mas acho que isso funciona.
DateTime _horaInicio = DateTime.Now;
DateTime _horaFim = Seu_Tempo_Decorrido;
Aí joga num textbox o seguinte:
TimeSpan resultado = _horaFim.Subtract(_horaInicio);
Você então terá sempre a var resultado com o resultado guardado. Depois é só indo acrescentando:
resultado += _horaFim.Subtract(_horaInicio);
Não testei, mas acho que isso funciona.
GOSTEI 0
Vinicius Biá
19/05/2013
Rapaz que encrenca, não da certo de jeito algum, ou eu vou ter que estudar mais C# pra tentar fazer isso, ou vou fazer em Delphi, coisa que eu já não quero fazer mais....
GOSTEI 0
Vinicius Biá
19/05/2013
Na verdade estou meio perdido de como é que vou encaixar seu código no meu, pois esta dando erros....
GOSTEI 0
Pjava
19/05/2013
O que não tá dando certo. Trabalhar com DateTime é chato mesmo, devido a parte hora. Acho que é nisso que você está apanhando, acho. Mande sua dúvida. É o mesmo código postado acima? Vai nos passando a dúvida, para podermos te ajudar melhor. Por exemplo, o que não está funcionando agora? O que está dando errado agora?
GOSTEI 0
Pjava
19/05/2013
O que é tempo. Um timer ou o que?
GOSTEI 0
Vinicius Biá
19/05/2013
OK, vamos lá, vou passar para você o código do meu cronometro, este código a principio só faz o contador de tempo funcionar, apertando no Inicio ele começa a rodar o tempo e apertado no Parar ele para o tempo, até ai tudo ok funcionando muito bem, porem oque eu quero é que quando for clicando no botão de Parar, ele me jogue dentro da minha TexBox o valor do tempo em que parou, e apos clicar novamente ele faça uma soma do valor existente com o valor atual
GOSTEI 0
Vinicius Biá
19/05/2013
OK, vamos lá, vou passar para você o código do meu cronometro, este código a principio só faz o contador de tempo funcionar, apertando no Inicio ele começa a rodar o tempo e apertado no Parar ele para o tempo, até ai tudo ok funcionando muito bem, porem oque eu quero é que quando for clicando no botão de Parar, ele me jogue dentro da minha TexBox o valor do tempo em que parou, e apos clicar novamente ele faça uma soma do valor existente com o valor atual
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
int contUm = 0, contDois = 0;
int hor, min, seg;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void iniciar(object sender, EventArgs e)
{
contDois++;
if (contDois % 2 == 1)
{
tempo.Start();
btnIniciar.Text = "Pausar";
}
else
{
tempo.Dispose();
btnIniciar.Text = "Iniciar";
}
}
private void parar(object sender, EventArgs e)
{
tempo.Stop();
contUm = 0;
contDois = 0;
lblTempo.Text = contUm.ToString() + "0:00:00";
btnIniciar.Text = "Iniciar";
txtTempo.Text = string.Format("{0:#,0#}:{1:#,0#}:{2:#,0#}", hor, min, seg);
}
private void temp(object sender, EventArgs e)
{
contUm++;
hor = (contUm / 3600);
min = (contUm % 3600) / 60;
seg = (contUm % 3600) % 60;
lblTempo.Text = string.Format("{0:#,0#}:{1:#,0#}:{2:#,0#}", hor, min, seg);
}
}
}
GOSTEI 0
Pjava
19/05/2013
Cara, não sei se é isso, mas veja esse código. Alterei um pouco seu código e fiz esse aqui.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Teste_Hora
{
public partial class Form1 : Form
{
int contUm = 0, contDois = 0;
int hor, min, seg;
private static TimeSpan tempoTotal = new TimeSpan();
int addend1;
int addend2;
int timeLeft;
public Form1()
{
InitializeComponent();
}
private void btnIniciar_Click(object sender, EventArgs e)
{
contDois++;
if (contDois % 2 == 1)
{
tempo.Start();
btnIniciar.Text = "Pausar";
}
else
{
tempo.Dispose();
btnIniciar.Text = "Iniciar";
}
}
private void tempo_Tick(object sender, EventArgs e)
{
timeLeft = timeLeft + 1;
addend1 = timeLeft;
lblTempo.Text = timeLeft + " seconds";
}
private void btnParar_Click(object sender, EventArgs e)
{
tempo.Stop();
contUm = 0;
contDois = 0;
lblTempo.Text = Convert.ToString(addend1);// contUm.ToString() + "0:00:00";
btnIniciar.Text = "Iniciar";
formataHora();
txtTempo.Text = string.Format("{0:#,0#}:{1:#,0#}:{2:#,0#}", hor, min, seg);
TimeSpan t = new TimeSpan();
t = TimeSpan.Parse(txtTempo.Text);
tempoTotal = TimeSpan.Parse(txtTempo.Text);
txtTempo.Text = Convert.ToString(t + tempoTotal);
}
private void formataHora()
{
hor = addend1 / 3600;
min = (addend1 % 3600) / 60;
seg = (addend1 % 3600) % 60;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Teste_Hora
{
public partial class Form1 : Form
{
int contUm = 0, contDois = 0;
int hor, min, seg;
private static TimeSpan tempoTotal = new TimeSpan();
int addend1;
int addend2;
int timeLeft;
public Form1()
{
InitializeComponent();
}
private void btnIniciar_Click(object sender, EventArgs e)
{
contDois++;
if (contDois % 2 == 1)
{
tempo.Start();
btnIniciar.Text = "Pausar";
}
else
{
tempo.Dispose();
btnIniciar.Text = "Iniciar";
}
}
private void tempo_Tick(object sender, EventArgs e)
{
timeLeft = timeLeft + 1;
addend1 = timeLeft;
lblTempo.Text = timeLeft + " seconds";
}
private void btnParar_Click(object sender, EventArgs e)
{
tempo.Stop();
contUm = 0;
contDois = 0;
lblTempo.Text = Convert.ToString(addend1);// contUm.ToString() + "0:00:00";
btnIniciar.Text = "Iniciar";
formataHora();
txtTempo.Text = string.Format("{0:#,0#}:{1:#,0#}:{2:#,0#}", hor, min, seg);
TimeSpan t = new TimeSpan();
t = TimeSpan.Parse(txtTempo.Text);
tempoTotal = TimeSpan.Parse(txtTempo.Text);
txtTempo.Text = Convert.ToString(t + tempoTotal);
}
private void formataHora()
{
hor = addend1 / 3600;
min = (addend1 % 3600) / 60;
seg = (addend1 % 3600) % 60;
}
}
}
GOSTEI 0
Vinicius Biá
19/05/2013
Rapaz consegui fazer oque queria, muito obrigado sua ajuda foi de grande importância...... vlw mesmo...
GOSTEI 0
José
19/05/2013
Olá amigo obrigado por sinalizar que conseguiu sanar sua duvida, sendo assim estou finalizando o tópico.
GOSTEI 0