How to get Timespan in Milliseconds - c#

I want to get the timespan in milliseconds by comparing two timestamps with DateTime.Now and the previous DateTime. I want to check if there is an event every 10 Milliseconds or later but the totalmilliseconds from DeltaT is like 188 or so. It is too high than I am expecting that is why I think there must be somethimg wrong. Or does everything look alright?
DateTime timestamp;
DateTime timestampAlt;
TimeSpan deltaT;
public void OnSensorChanged(SensorEvent e)
{
timestamp = System.DateTime.Now;
deltaT = timestamp - timestampAlt;
if (deltaT.TotalSeconds <= 0.01)
{
return;
}
UPDATE:
I really appreciate all of you answers but I think there is a misunderstanding (my mistake sry). So here again:
Whenever the listener recognizes an event, I want to save the timestamp and compare with the timespamp of the event before. If there is a gap of more than 10 Milliseconds between the 2 events, then I do want to know more about this new event. If not, I dont even want to continue and will leave by a return.
public void OnSensorChanged(SensorEvent e)
{
timestamp = System.DateTime.Now;
deltaT = timestamp - timestampAlt;
//int deltaT2 = timestamp.Millisecond - timestampAlt.Millisecond;
String timestampStr = timestamp.ToString("ff");
String timestampStrA = timestampAlt.ToString("ff");
if (deltaT.TotalMilliseconds <= 10 || deltaT.TotalMilliseconds <= -10) //deltaT.Seconds <= 0.01
{
return;
}
timestampAlt = timestamp;
newValue = e.Values[2];
//if (buffer[99] != 0.00)
// if last element of list is empty, add elements to buffer
if (buffer.Count <=99)
{
buffer.Add(newValue);
zeitbuffer.Add(timestamp);
}
else
{
Ableitung(DeltaBuffer(), DeltaTime()); // if last index of list is filled, do that function
}
if (e.Values[2] >= 11)
{
try
{
lock (_syncLock)
{
String z2 = newValue.ToString("0.0");
//noteInt2 = Convert.ToInt32(newValue);
try
{
_sensorTextView2.Text = string.Format("Note: {0}", z2 );
eventcounter.Add(z2);

You can use deltaT.TotalMilliseconds which expresses your delta in milliseconds. Therefore your check could be rewritten as
if (deltaT.TotalMilliseconds <= 10)
{
return;
}
10 is a value I inferred. It might not be what you need, but your question is partial. This answer addresses your particular question, however if you need to measure the duration of a task you should use the Stopwatch class, which is designed for that purpose.

if you want to fire an event every n-Seconds you can use a timer that fires an event when he elapses:
Timer timer = new Timer();
timer.Interval = 100;
timer.Elapsed += YourAmasingEvent;
timer.Start();
private void YourAmasingEvent(object sender, ElapsedEventArgs e)
{
//do something here
(sender as Timer).Start();
}
Using your code:
I guess you want to wait until the time elapsed in this case you would have to use a loop like this:
timestamp = System.DateTime.Now;
deltaT = timestamp - timestampAlt;
while(true)
{
if (deltaT.TotalSeconds <= 0.01)
{
return;
}
timestamp = System.DateTime.Now;
deltaT = timestamp - timestampAlt;
}

Related

Change Timer interval value on the fly

I have a CSV file that will read LineByLine ... like :
0
2.25
5
5.30
I need to Timer interval to change ... but there is no effect when its changed...
I need to fill a textbox.
please let me know your solution
while ((currentLine = sr.ReadLine()) != null)
{
string[] temp = currentLine.Split(',');
timerinterval = (int)(Convert.ToDouble(temp[0])*1000);
if ((int)(Convert.ToDouble(temp[0]) * 1000) != 0)
{
mytimer.Stop();
mytimer.Interval = (int)(Convert.ToDouble(temp[0]) * 1000);
mytimer.Start();
txtCurrentLine.Text = currentLine;
txtTime.Text = timerinterval.ToString();
}
}
public TimeCapture
{
public TimeCapture() => Start = DateTime.Now;
public Start { get; }
public TimeSpan Duration => DateTime.Now.Subtract(Start).Value.TotalSeconds;
}
Then when you intend to read each line.
var timer = new TimeCapture();
while(...)
{
...
txtTime.Text = timer.Duration;
}
Now as you iterate every single line you're capturing the duration as it is reading each line. If you are interested in line by line duration, simply create a new object per line, then put duration and it'll be for the linear code block.

Multiple countdown timer in listview C# duplicating

I'm new to C#.
I'm trying to make a simple task reminder program.
The problem is, when I try to add a countdown for deadline time, it won't work correctly.
My first task countdown will be overwritten by my second task countdown, the same case when I add the third task and so on.
Here is the code of the correlating part.
private void buttonSave_Click(object sender, EventArgs e)
{
if (this.textBox_Task.Text != "")
{
listView1.View = View.Details;
ListViewItem lvwItem = listView1.Items.Add(dateTimePicker1.Text);
var day = dateTimePicker1.Value.Day;
var month = dateTimePicker1.Value.Month;
var year = dateTimePicker1.Value.Year;
endTime = new DateTime(year,month,day);
//Console.WriteLine(day);
//Console.WriteLine(month);
//Console.WriteLine(year);
//Console.WriteLine(dTime
Timer t = new Timer();
t.Interval = 500;
t.Tick += new EventHandler(t_Tick);
t.Start();
lvwItem.SubItems.Add(textBox_Task.Text);
lvwItem.SubItems.Add(textBox_Note.Text);
lvwItem.SubItems.Add("");
this.dateTimePicker1.Focus();
this.textBox_Note.Focus();
this.textBox_Task.Focus();
this.textBox_Task.Clear();
this.textBox_Note.Clear();
}
else
{
MessageBox.Show("Please enter a task to add.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.textBox_Task.Clear();
this.textBox_Note.Clear();
}
}
void t_Tick(object sender, EventArgs e)
{
TimeSpan ts = endTime.Subtract(DateTime.Now);
var hari = dateTimePicker1.Value.Day;
Console.WriteLine(ts.Days);
for (int i = 0; i < listView1.Items.Count; i++)
{
if (ts.Days == 0)
{
listView1.Items[i].SubItems[3].Text = "DEADLINE";
}
else
{
listView1.Items[i].SubItems[3].Text = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds to go'");
}
}
}
It would be much appreciated for anyone who willing to help.
Thanks in advance.
Here is the link to the picture of my problem
What you are doing now is on each button click override the current endTime object by a new one like:
endTime = new DateTime(year,month,day);
If you assign a new DateTime object to endTime. You override the old one. So the first button click will work but the second will create a new object of DateTime and assign it to endTime. Next you are calculating the time difference on that one object DateTime. So it is logic that it will be the same time for each listview items
If you want to have more than one DateTime use a List to store it in like
List<DateTime> _times = new List<DateTime>();
In the button click method add the DateTime to the list
// here add the datetime to the list
DateTime dateTime = new DateTime(year, month, day);
_times.Add(dateTime);
Next you can loop thru the dates and calculate for each one the time difference in the tick method:
foreach (var dateTime in _times)
{
TimeSpan ts = dateTime.Subtract(DateTime.Now);
// etc..
}
Also you are creating a timer for each time to calculate after 500 ms. You now can use one timer this is more efficient than crating one for each time. Just assign this in the constructor
public Form1()
{
InitializeComponent();
Timer t = new Timer();
t.Interval = 500;
t.Tick += new EventHandler(t_Tick);
t.Start();
}
Whole code
public partial class Form1 : Form
{
// This is the list where the DateTimes are stored so you can have more values
List<DateTime> _times = new List<DateTime>();
public Form1()
{
InitializeComponent();
// Assign the timer here
Timer t = new Timer();
t.Interval = 500;
t.Tick += new EventHandler(t_Tick);
t.Start();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (this.textBox_Task.Text != "")
{
listView1.View = View.Details;
ListViewItem lvwItem = listView1.Items.Add(dateTimePicker1.Text);
var day = dateTimePicker1.Value.Day;
var month = dateTimePicker1.Value.Month;
var year = dateTimePicker1.Value.Year;
// Add Datetime to list
DateTime dateTime = new DateTime(year, month, day);
_times.Add(dateTime);
lvwItem.SubItems.Add(textBox_Task.Text);
lvwItem.SubItems.Add(textBox_Note.Text);
lvwItem.SubItems.Add("");
this.dateTimePicker1.Focus();
this.textBox_Note.Focus();
this.textBox_Task.Focus();
this.textBox_Task.Clear();
this.textBox_Note.Clear();
}
else
{
MessageBox.Show("Please enter a task to add.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.textBox_Task.Clear();
this.textBox_Note.Clear();
}
}
void t_Tick(object sender, EventArgs e)
{
// loop thru all datetimes and calculate the diffrence
foreach (var dateTime in _times)
{
// Call the specific date and subtract on it
TimeSpan ts = dateTime.Subtract(DateTime.Now);
var hari = dateTimePicker1.Value.Day;
Console.WriteLine(ts.Days);
for (int i = 0; i < listView1.Items.Count; i++)
{
if (ts.Days == 0)
{
listView1.Items[i].SubItems[3].Text = "DEADLINE";
}
else
{
listView1.Items[i].SubItems[3].Text = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds to go'");
}
}
}
}
}

How to create an advanced countdown timer

Well, this question is related to this one, so you guys can understand it better
How to convert the "time" from DateTime into int?
My Answer to it:
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value + "";
string value = dataGridView1.Rows[0].Cells[2].Value + "";
lblLeft.Text = value.Split(' ')[1];
textStatus.Text = "";
DateTime timeConvert;
DateTime.TryParse(value, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
lblSoma.Text = timeSpan.ToString();
timer2.Start();
According to the answer I wrote right there, I want to know if there's a way I can apply it to a timer and do the DataGrid values (converted) turn into a timer value. So if I press a button they start the countdown.
I have tried to insert this code inside the timer:
private void timer2_Tick(object sender, EventArgs e)
{
string timeOp = dataGridView1.Rows[0].Cells[2].Value + "";
DateTime timeConvert;
DateTime dateTime = DateTime.Now;
DateTime.TryParse(timeOp, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
if (time > 0)
{
time = time - 1000; //(millisec)
lblCountdown.text = time.ToString();
}
}
didn't count down or anything, does someone has an idea of what should I do or why it isn't working?
The value of time never changes, because you create it again fresh each time.
To solve this, you have to declare the variable you decrement outside of the Tick event.
Put these two variables on your form:
private int milliSecondsLeft = 0;
private bool timeSet = false;
Then change the 'tick' event to this:
private void timer2_Tick(object sender, EventArgs e)
{
if (!timeSet) // only get the value once
{
string dateTimeFromGrid = "4/29/2016 5:00:00 AM"; //hardcoded for simplicity, get the string from your grid
DateTime fromGrid;
DateTime.TryParse(dateTimeFromGrid, out fromGrid);
milliSecondsLeft = (int)fromGrid.TimeOfDay.TotalMilliseconds;
timeSet = true;
}
milliSecondsLeft = milliSecondsLeft - 100; // timer's default Interval is 100 milliseconds
if (milliSecondsLeft > 0)
{
var span = new TimeSpan(0, 0, 0, 0, milliSecondsLeft);
lblCountdown.Text = span.ToString(#"hh\:mm\:ss");
}
else
{
timer2.Stop();
}
}
Make sure

Windows Phone countdown app

I am trying to do two things:
On Christmas day, invoke a method whenever the page is navigated to.
After Christmas day, set the christmasDay DateTime to +1 year (so the countdown "resets").
Here is my code:
private void OnTick(object sender, EventArgs e)
{
DateTime christmasDay;
DateTime.TryParse("11/17/13", out christmasDay);
var timeLeft = christmasDay - DateTime.Now;
int x = DateTime.Now.Year - christmasDay.Year;
if (DateTime.Now > christmasDay)
{
if (x == 0)
x += 1;
christmasDay.AddYears(x);
if (DateTime.Now.Month == christmasDay.Month && DateTime.Now.Day == christmasDay.Day)
{
itsChristmas();
}
}
countdownText.Text = String.Format("{0:D2} : {1:D2} : {2:D2} : {3:D2}", timeLeft.Days, timeLeft.Hours, timeLeft.Minutes, timeLeft.Seconds);
}
When I set the date to TODAY, the "itsChristmas()" method works...but I don't actually want it to be invoked on each tick of the countdown. I tried putting it in the constructor of the page but that doesn't work. Any ideas?
The second problem is that if I set the date to a day before today, it gives me negative numbers. I don't know what is wrong with my code that this is happening. :(
Your solution is quite complex. You could solve it like this.
private void OnTick(object sender, EventArgs e)
{
var now = DateTime.Now;
var christmasDay = NextChristmas();
if (now.Date < christmasDay.Date)
{
// it's not christmas yet, nothing happens
}
if (now.Date == christmasDay.Date)
{
// it's christmas, do your thing
itsChristmas();
}
}
private DateTime NextChristmas()
{
var thisYearsChristmas = new DateTime(DateTime.Now.Year, 12, 25);
if (DateTime.Now.Date <= thisYearsChristmas.Date) return thisYearsChristmas;
return thisYearsChristmas.AddYears(1);
}
The if statemements can be written more consise but I elaborated on them to make clear what happens.

How to compare time in c#?

for (int i = 0; i <= 10; i++)
{
if (5 seconds have passed)
{
do something;
}
}
How can I check if 5 seconds have passed? If 5 seconds have passed for example, it "does something" , then again if more 5 seconds have passed, it does the same thing again, and so on.
And important: If I should use date & time to do it, it should not be a specific time, it should be automatic.
You need a reference start date and a "now" date;
if(startDate.addSeconds(5) < DateTime.Now) do something
If I understood well the situation could be like:
DateTime startDate = DateTime.Now;
for (int i = 0; i <= 10; i++)
{
//do something that can take a long time
//...
//..
if(startDate.addSeconds(5) < DateTime.Now) //5 seconds have passed
{
//do something else
}
}
Thread.Sleep(5000); But this will block your application. You could use a Timer.
For .NET 4.5 you could use the await Task.Delay(5000);
I think FelipeP made a great statement..
But the code you gave, and the description of the problem aren't the same.
The code says, if time is passed.
Your description says the loop must wait until the time is passed.
Update:
System.Windows.Forms.Timer _timer = new System.Windows.Forms.Timer();
void CreateTimer()
{
_timer = new System.Windows.Forms.Timer();
_timer.Tick += new EventHandler(_timer_Tick);
_timer.Interval = 5000;
_timer.Enabled = true;
}
void _timer_Tick(object sender, EventArgs e)
{
// do something.
}

Categories

Resources