How to calculate time difference (subtract time) in C#? - c#

I am creating program to measure vacuum value with Arduino and display it in the form that created with C#.
I want to store time as an constant. It is starting time of the program. I assigned it with "Connect" button. When I clicked, time value is storing.
Then I am using "timer tick" method to see measured values instantly. Also, DateTime.Now shows me instant system time. It is changing like a clock.
click here to see the picture
Here is the Connect button's code;
public void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
try
{
if (comboBox1.Text == "")
{
MessageBox.Show("Please select the port name!");
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.ReadBufferSize = 8;
serialPort1.Open();
timeval.Clear();
button1.Enabled = false;
button2.Enabled = true;
timer1.Start();
DateTime myDateTime = DateTime.Now; //It stores the instant time information when button is clicked.
label14.Text = myDateTime.ToString(); // shows in the label
//serialPort1.ReadTimeout = 300;
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorized Access!");
}
}
Here is the timer tick's code;
public void timer1_Tick(object sender, EventArgs e)
{
label12.Text = DateTime.Now.ToString();
//TimeSpan time_difference = DateTime.Now - myDateTime; // trying to calculate time difference.
//double saniye = time_difference.Seconds;
//double dakika = time_difference.Minutes;
//label10.Text = (Math.Round(saniye)).ToString();
//label16.Text = (Math.Round(dakika)).ToString();
new_data = 756 * (float.Parse(data) - 1023) / 1023;
sensorval.Add(Math.Round(new_data, 1));
all_data.Add(Math.Round(new_data, 1));
textBox1.Text = Convert.ToString(Math.Round(new_data, 2));
all_data.Sort();
var peak_vacuum = all_data[0];
textBox4.Text = peak_vacuum.ToString();
if (sensorval.Count % 100 == 0)
{
sensorval.Sort();
var find_max = sensorval[0];
var find_min = sensorval[sensorval.Count - 1];
textBox3.Text = find_min.ToString();
textBox2.Text = find_max.ToString();
sensorval.RemoveRange(0, 99);
}
}
I could not calculate time difference because myDateTime variable is calculating in button2 and defined in button2 method. But DateTime.Now is defined in timer tick method. So, I am getting an error that "The name 'myDateTime' does not exist in the current content." in the timer tick method.
By the way, I tried to use counter in the timer tick to see the seconds after program works. It was not so accurate. It was slower then the real time. So, I choose above method.
Thank you in advance.

I thinks its like what you want.
public partial class Form1 : Form
{
// accessable from all methods, events on Form1
private DateTime myDateTime;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myDateTime = DateTime.Now;
// other codes
}
private void timer1_Tick(object sender, EventArgs e)
{
// other codes
}
private void button2_Click(object sender, EventArgs e)
{
// other codes
var diffrenceSpan = DateTime.Now - myDateTime;
var hours = diffrenceSpan.Hours;
var minutes = diffrenceSpan.Minutes;
var seconds = diffrenceSpan.Seconds;
}
}
gits project links

Related

How To Make a StopWatch With C#

I just want to ask that if I can make a stopwatch with C# I tried:
private void button2_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
int st = 00;
int m = 00;
string stime = "00:00";
if(st == 60)
{
m++;
st = 00;
}
else
{
st++;
}
if (m == 60)
{
m = 00;
}
if(st < 10)
{
st = 0 + st;
}
if(m < 10)
{
m = 0 + m;
}
stime = m.ToString() + ":" + st.ToString();
label3.Text = stime;
}
this but it didn't worked. My timer is setted up and the interval of the timer is 1000ms. Can someone help me?
It looks to me, that you are more likly to make a watch rather than a stopwatch?
If you're making a stopwatch, I think you need a field/property in your class that holds the starting time:
private DateTime _start;
private void button2_Click(object sender, EventArgs e)
{
_start = DateTime.Now;
timer1.Start();
}
and then in timer1_Tick you can do:
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan duration = DateTime.Now - _start;
label3.Text = duration.ToString(<some format string>);
}
It seems that your current code in timer1_Tick only has local variables and therefore always will produce the same time? :-)

Form timer doesn't start

So I just started learning C# and using forms. I have been able to create a digital clock and tinker with this and that, but now I'm trying to make a basic UI for a derpy game and my timer doesn't work.
First - what I'm trying to accomplish: A simple decrementing timer from 60 seconds (*clock style (mm:ss)).
Second, here's what I have:
public partial class Form1 : Form
{
private int counter = 60;
public Form1()
{
InitializeComponent();
label1.Text = TimeSpan.FromMinutes(1).ToString("m\\:ss");
}
private void pictureBox2_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
{
timer1.Stop();
label1.Text = counter.ToString();
MessageBox.Show("Time's Up!!");
}
}
private void label1_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
var counter = (TimeSpan.FromMinutes(1)).ToString("m\\:ss");
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
label1.Text = counter.ToString();
}
}
Appreciate the feedback and knowledge!
From the codes that I see, your timer is working but you are not updating it in each count, you are updating when the timer finishes -
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
{
timer1.Stop();
label1.Text = counter.ToString(); // *** Look here
MessageBox.Show("Time's Up!!");
}
}
You should update the timer in each tick, so take the update label code out of the if block -
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
label1.Text = counter.ToString(); // should work
if (counter == 0)
{
timer1.Stop();
MessageBox.Show("Time's Up!!");
}
}
and also reset the counter in each cycle -
private void label1_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
var counter = (TimeSpan.FromMinutes(1)).ToString("m\\:ss");
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
label1.Text = counter.ToString();
this.counter = 60
}
NOTE: I am really not sure if this code will throw any access
violation error, due to updating the UI in a different thread or not.
If so, then you have to use async/await or events/delegates to
update UI.
Let me know, if this throws error, then I will give you the async/await version.
This works fine for me. I would give progress updates as the time is countdown to show that it is working. For example, if you did this in label, you could do something like the following:
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
label1.Text = counter.ToString();
if (counter == 0)
{
timer1.Stop();
MessageBox.Show("Time's Up!!");
}
}
Notice that the label1.Text = counter.ToString(); line has been moved before the counter == 0 check, so that it is able to provide feedback for all counter values.
As well, you may accidentally launch several timer1 instances if you do not keep track of how many you spawn using new Timer(). There are various ways to do this, but you could simply check whether timer1 already exists and counter == 0 before creating a new instance. You could perform this check as a guard clause (ie. return if either of those conditions are matched).
private void label1_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
if (timer1 == null || (timer1 != null && counter == 0)) return;
counter = (TimeSpan.FromMinutes(1)).ToString("m\\:ss");
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
label1.Text = counter.ToString();
}
If you want this countdown to start automatically, you can put this directly into the constructor, or put it into another method and call it from the constructor like so:
public Form1()
{
InitializeComponent();
StartCountdown();
}
private void StartCountdown()
{
var startTime = DateTime.Now;
/* the rest of your original label1_Click code goes here ... */
}

How to display seconds using TimeSpan on Timer Tick Event

I am using below code to display time left in hh:mm:ss format for example if duration is 30min, it will show like this 00:30:00 and after 1 min it will show 00:29:00, how can i also display the remaining seconds and decrease them accordingly.,
Edit
I tried timer1.Interval = 1000; and
examTime = examTime.Subtract(TimeSpan.FromSeconds(1));
But its not showing me seconds reducing each second, How do i do it ?
public SubjectExamStart()
{
InitializeComponent();
examTime = TimeSpan.FromMinutes(double.Parse(conf[1]));
label1.Text = examTime.ToString();
timer1.Interval = 60 * 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sender == timer1)
{
if (examTime.TotalMinutes > 0)
{
examTime = examTime.Subtract(TimeSpan.FromMinutes(1));
label1.Text = examTime.ToString();
}
else
{
timer1.Stop();
MessageBox.Show("Exam Time is Finished");
}
}
}
Instead of Subtracting TimeSpan.FromMinutes you need to subtract from TimeSpan.FromSeconds
public SubjectExamStart()
{
InitializeComponent();
examTime = TimeSpan.FromSeconds(double.Parse(conf[1]));
label1.Text = examTime.ToString();
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sender == timer1)
{
if (examTime.TotalMinutes > 0)
{
examTime = examTime.Subtract(TimeSpan.FromSeconds(1));
label1.Text = examTime.ToString();
}
else
{
timer1.Stop();
MessageBox.Show("Exam Time is Finished");
}
}
}
If you want to format the Time Span value while assigning to Label... You can use below..
label1.Text = examTime.ToString(#"dd\.hh\:mm\:ss");
To do this properly, you will need to keep a track of when the timer was started
DateTime examStartTime;
System.Windows.Forms.Timer runTimer;
TimeSpan totalExamTime = new TimeSpan(1, 30, 0); // Set exam time to 1 hour 30 minutes.
if (runTimer == null)
runTimer = new System.Windows.Forms.Timer();
runTimer.Interval = 200;
runTimer.Tick -= new EventHandler(runTimerTick);
runTimer.Tick += new EventHandler(runTimerTick);
examStartTime = DateTime.Now;
runTimer.Start();
Then in the event handler you can do:
public void runTimerTick(object sender, EventArgs e)
{
TimeSpan currentExamTime = DateTime.Now - examStartTime;
if (currentExamTime > totalExamTime)
{
MessageBox.Show("Exam Time is Finished");
runTimer.Stop();
runTimer.Tick -= new EventHandler(runTimerTick);
runTimer.Dispose();
}
}
I hope this helps.
try this hope this will work for u
set timer interval=1000
minremain=1200000; //Should be in milisecond
timerplurg.satrt();
private void timerplurg_Tick(object sender, EventArgs e)
{
minremain = minremain - 1000; //substring One second from total time
string Sec = string.Empty;
if (minremain <= 0)
{
lblpurgingTimer.Text = "";
timerplurg.Stop();
return;
}
else
{
var timeSpan = TimeSpan.FromMilliseconds(Convert.ToDouble(minremain));
var seconds = timeSpan.Seconds;
if (seconds.ToString().Length.Equals(1))
{
Sec = "0" + seconds.ToString();
}
else
{
Sec = seconds.ToString();
}
string Totaltime = "Remaing Second: " + Sec;
lblpurgingTimer.Text = Totaltime;
}

How to do a 30 minute count down timer

I want my textbox1.Text to countdown for 30 minutes. So far I have this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Timer timeX = new Timer();
timeX.Interval = 1800000;
timeX.Tick += new EventHandler(timeX_Tick);
}
void timeX_Tick(object sender, EventArgs e)
{
// what do i put here?
}
}
However I'm now stumped. I checked Google for answers but couldn't find one matching my question.
Here's a simple example similar to the code you posted:
using System;
using System.Windows.Forms;
namespace StackOverflowCountDown
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.Text = TimeSpan.FromMinutes(30).ToString();
}
private void Form1_Load(object sender, EventArgs e) { }
private void textBox1_TextChanged(object sender, EventArgs e) { }
private void button1_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
var timer = new Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
textBox1.Text =
(TimeSpan.FromMinutes(30) - (DateTime.Now - startTime))
.ToString("hh\\:mm\\:ss");
timer.Enabled = true;
}
}
}
Easiest thing you can do, is use a 1 minute timer:
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 countdowntimer
{
public partial class Form1 : Form
{
private Timer timeX;
private int minutesLeft;
public Form1()
{
InitializeComponent();
timeX = new Timer(){Interval = 60000};
timeX.Tick += new EventHandler(timeX_Tick);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
minutesLeft=30;
timeX.Start();
}
void timeX_Tick(object sender, EventArgs e)
{
if(minutesLeft--<=0)
{
timeX.Stop();
// Done!
}
else
{
// Not done yet...
}
textBox1.Text = minutesLeft + " mins remaining";
}
}
}
If all you want to do is set the value of your Texbox to count down from 30 Minutes. You will first need to change your timer interval to something smaller than 30Minutes. Something like timeX.Interval = 1000; which will fire every second. then set up your event like so:
int OrigTime = 1800;
void timeX_Tick(object sender, EventArgs e)
{
OrigTime--;
textBox1.Text = OrigTime/60 + ":" + ((OrigTime % 60) >= 10 ? (OrigTime % 60).ToString() : "0" + OrigTime % 60);
}
Also in your button click, you must add the following line: timeX.Enabled = true; In order to start the timer.
Your code will only get one event fired, once the 30 minutes has passed. In order to keep updating your UI continuously you'll have to make the events more frequent and add a condition inside the event handler to tell the count-down to stop once 30 minutes has passed.
You can do the time calculations easily by using TimeSpan and DateTime.
You'll also want to make sure your UI code runs on the UI thread, hence the Invoke.
timeX.Interval = 500;
...
TimeSpan timeSpan = TimeSpan.FromMinutes(30);
DataTime startedAt = DateTime.Now;
void timeX_Tick(object sender, EventArgs e)
{
if ((DateTime.Now - startedAt)<timeSpan){
Invoke(()=>{
TimeSpan remaining = timeSpan - (DateTime.Now - startedAt);
textBox.Text = remaining.ToString();
});
} else
timeX.Stop();
}
try this hope this will work for u
set timer interval=1000
minremain=1800000; //Should be in milisecond
timerplurg.satrt();
private void timerplurg_Tick(object sender, EventArgs e)
{
minremain = minremain - 1000;
string Sec = string.Empty;
string Min = string.Empty;
if (minremain <= 0)
{
lblpurgingTimer.Text = "";
timerplurg.Stop();
return;
}
else
{
var timeSpan = TimeSpan.FromMilliseconds(Convert.ToDouble(minremain));
var seconds = timeSpan.Seconds;
var minutes = timeSpan.Minutes;
if (seconds.ToString().Length.Equals(1))
{
Sec = "0" + seconds.ToString();
}
else
{
Sec = seconds.ToString();
}
if (minutes.ToString().Length.Equals(1))
{
Min = "0" + minutes.ToString();
}
else
{
Min = minutes.ToString();
}
string Totaltime = "Purge Remaing Time: " + Min + ":" + Sec;
lblpurgingTimer.Text = Totaltime;
}
}

c# counting clicks

I have a timer and in 30 minutes I want to count clicks and show it in a textbox. but how? here is timer code:
decimal sure = 10;
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
sure--;
label3.Text = sure.ToString();
if (sure == 0)
{
timer1.Stop();
MessageBox.Show("Süre doldu");
}
}
Declare your clickCounter at global, and raise your counter++ in Mouse Click Event.
If you do it more specific, you can use Background Worker, to track time.
and use Application.DoEvents() to write remaining to to textBox
Put a button, 2 labels, and a timer. rename labels with lblClickCount and lblRemainingTime
private int clickCounter = 0;
private void button1_Click(object sender, EventArgs e)
{
clickCounter++;
lblClickCount.Text = clickCounter.ToString();
}
decimal sure = 10;
private void timer1_Tick(object sender, EventArgs e)
{
sure--;
lblRemainingTime.Text = sure.ToString();
Application.DoEvents();
if (sure == 0)
{
timer1.Stop();
MessageBox.Show("Süre doldu. Toplam tiklama sayisi:" + clickCounter.ToString());
}
}
If you wanted to reuse buttoN1 to count the clicks but not Start new timer you can add a if around the code you want to protect.
bool hasTimerStarted = false;
int numberOfClicks = 0;
private void button1_Click(object sender, EventArgs e)
{
if(!hasTimerStarted)
{
button1.Enabled = true;
timer1.Start();
hasTimerStarted = true;
}
++numberOfClicks;
}
When the timer expires you reset the count and if the timer has started.
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
label3.Text = elapsedTime;
labelClicks.Text = "User clicked " + clicksNo.toString() + "nt times..";
if (stopWatch.ElapsedMilliseconds >= this.minutes * 60 * 1000)
{
timer1.Stop();
MessageBox.Show("Time elapsed.");
hasTimerStarted = false;
numberOfClicks = 0;
}
}

Categories

Resources