Windows Phone countdown app - c#

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.

Related

How to validate if the input time is within the given time range in asp.net C#?

My time range is 08:00 AM to 03:00 PM.
If the selected input time does not exist within this range it should throw an error message.
How to do this?
Can anybody help me out?
protected void txtTimeIn_TextChanged(object sender, EventArgs e)
{
DateTime time = Convert.ToDateTime(txtTimeIn.Text);
TimeSpan start = new TimeSpan(8, 0, 0);
TimeSpan end = new TimeSpan(15, 0, 0);
TimeSpan now = new TimeSpan(time.Ticks);
if ((now > start) && (now < end))
{
lblIN.Visible = false;
}
else
{
lblIN.Visible = true;
}
}
When i select the wrong time the label is displayed, but once i change and select the correct time the label is not disappearing.
public void Page_Load(object sender, EventArgs e)
{
TimeSpan startTime = new TimeSpan(8, 0, 0); // 8 AM
TimeSpan endTime = new TimeSpan(15, 0, 0); // 3 PM
if (DateTime.Now.TimeOfDay > startTime && DateTime.Now.TimeOfDay < endTime)
{
// Execute logic
}
}
Here is a quick and easy solution to check against the current DateTime. Obviously you said you have a "selected date" but I don't see that anywher, so just convert that to a DateTime if needed.

How to get Timespan in Milliseconds

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;
}

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

Telerik Rad Calendar - Is Changing Data Source Possible?

I'm trying to change the dates displayed in a RadCalendar. For example, I want it to begin 2 weeks before the current date and ends two weeks after the current date. Is it possible?
I was able to change the text displayed in the cells (to display the "new" date) but the "OnClick" methods still sends the "old" date.
OnDayRender I added :
e.Cell.Text = "" + _calStartDate.Day.ToString() + "";
_calStartDate = _calStartDate.AddDays(1);
But the calendar still thinks that the new dates are the old one, so the "SelectedDate" method returns the "old" date and the date selected is not the current date.
Is there a way to just pass a new list of dates, which would be easier?
UPDATE / Solution:
I was able to make it work like that:
private int rowCounter = 0;
private int rowHeaderCnt = 0;
private DateTime _startDate;
private DateTime _endDate;
private DateTime _calStartDate;
private DateTime _calEndDate;
protected void radCalendar_DayRender(object sender, Telerik.Web.UI.Calendar.DayRenderEventArgs e)
{
TableRow tr = (TableRow)e.Cell.Parent;
Table table = (Table)tr.Parent;
if (e.Day.Date.CompareTo(_calStartDate) < 0)
{
((TableRow)(e.Cell.Parent)).Style["display"] = "none";
}
else if (e.Day.Date.CompareTo(_calEndDate) > 0)
{
((TableRow)(e.Cell.Parent)).Style["display"] = "none";
}
else if (e.Day.Date.DayOfWeek == DayOfWeek.Sunday)
{
// This part will change the week number cell (if you don't display it, hide this part)
rowCounter++;
TableCell cellRowHeader = ((TableRow)(e.Cell.Parent)).Cells[0];
cellRowHeader.Text = rowCounter.ToString();
}
}
protected void Page_Load(object sender, EventArgs e)
{
radCalendar.RangeMinDate = _startDate;
radCalendar.RangeMaxDate = _endDate;
}
protected void radCalendar_HeaderCellRender(object sender, Telerik.Web.UI.Calendar.HeaderCellRenderEventArgs e)
{
if (e.HeaderType == Telerik.Web.UI.Calendar.HeaderType.Row)
{
rowHeaderCnt++;
e.Cell.Text = " " + rowHeaderCnt;
}
if (e.HeaderType == Telerik.Web.UI.Calendar.HeaderType.Column)
{
TableRow row = ((TableRow)(e.Cell.Parent));
row.Cells[0].Text = " " + StringUtil.getStringByLanguage("Week", "Sem.") + " ";
}
}
protected void raCalendar_SelectionChanged(object sender, Telerik.Web.UI.Calendar.SelectedDatesEventArgs e)
{
DateTime startDate = new DateTime();
DateTime endDate = new DateTime();
String url = String.Empty;
if (e.SelectedDates.Count == 1)
{
startDate = e.SelectedDates[0].Date;
endDate = e.SelectedDates[0].Date;
}
else
{
startDate = e.SelectedDates[0].Date;
endDate = e.SelectedDates[e.SelectedDates.Count - 1].Date;
}
// ... add code here with startDate and endDate
}
public void initCalendar(DateTime startDate, DateTime endDate)
{
this._startDate = startDate;
this._endDate = endDate;
this._calStartDate = startDate;
this._calEndDate = endDate;
while (this._calStartDate.DayOfWeek != DayOfWeek.Sunday)
{
this._calStartDate = this._calStartDate.AddDays(-1);
}
while (this._calEndDate.DayOfWeek != DayOfWeek.Saturday)
{
this._calEndDate = this._calEndDate.AddDays(1);
}
}
Based on my attempts, you can get very close to this setup. You have to use some trickery though, as the functionality, as far as I can tell, is not built into the calendar to only display the dates as you have asked for.
On page load:
protected void Page_Load(object sender, EventArgs e)
{
RadCalendar1.RangeMinDate = DateTime.Now.AddDays(-14);
RadCalendar1.RangeMaxDate = DateTime.Now.AddDays(14);
RadCalendar1.FirstDayOfWeek = (FirstDayOfWeek)DateTime.Now.AddDays(-14).DayOfWeek;
}
On day render:
protected void RadCalendar1_DayRender1(object sender, Telerik.Web.UI.Calendar.DayRenderEventArgs e)
{
if (e.Day.Date >= RadCalendar1.RangeMinDate.Date && e.Day.Date <= RadCalendar1.RangeMaxDate.Date)
{
e.Cell.Visible = true;
}
else
{
e.Cell.Visible = false;
}
}
This will get you an initial calendar load that shows 2 weeks back and 2 weeks forward and only allow the user to select inside that date. What it does not do, and I'd guess to be a separate question, is it does not execute the hiding of the dates outside the range when you page to the following month.
You must be aware that the format for the calendar must be 42 days, as per the design of the tool itself. That is why you see the blank line on top, as we are hiding those days. To my knowledge you can not remove them, only hide them or display them but not allow them to be clicked.

Time Elapsed/StopWatch

I want to create an ASP.NET WinForms application that tracks time on task. I need to be able to write the form so that I can add the task to the database, open it in a new tab, and be able to start, pause, and stop the task. When I'm finished, I need to calculate the time taken to complete the task. I would like to have a view of the stopwatch running on the page, showing hours:min:sec updating every second via AJAX. I have already looked on the web at TimeSpan, DateTime, StopWatch, etc. and I can't seem to find anything that works for me. I started with a simple form with start and stop buttons. The _click event for the start button assigns my DateTime variable 'startTime = DateTime.Now' and the _click event for the stop button assigns my DateTime variable 'endTime = DateTime.Now'. I then use a TimeSpan 'elapsed' to calculate TimeSpan 'elapsed = (endTime - startTime). When I update a label to show the time elapsed, I'm expecting to get just the seconds that have gone by, but I get the entire DateTime string. Below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
namespace CS_StopWatch
{
public partial class Default : System.Web.UI.Page
{
//public Stopwatch myStopWatch = new Stopwatch();
public DateTime startTime;
public DateTime endTime;
public TimeSpan ts_timeElapsed;
public string s_timeElapsed;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void StartButton_Click(object sender, EventArgs e)
{
//myStopWatch.Start();
startTime = DateTime.Now;
}
protected void StopButton_Click(object sender, EventArgs e)
{
//myStopWatch.Stop();
//ElapsedLabel.Text = "Time Elapsed: " + myStopWatch.Elapsed;
endTime = DateTime.Now;
ts_timeElapsed = (endTime - startTime);
s_timeElapsed = GetElapsedTimeString();
ElapsedLabel.Text = "Time Elapsed: " + s_timeElapsed;
}
public string GetElapsedTimeString()
{
int days = ts_timeElapsed.Days;
double hours = ts_timeElapsed.Hours;
double mins = ts_timeElapsed.Minutes;
double secs = ts_timeElapsed.Seconds;
string x = "";
if (days != 0)
{
x += days.ToString() + ":";
}
if (hours != 0)
{
x += hours.ToString() + ":";
}
if (mins != 0)
{
x += mins.ToString() + ":";
}
if (secs != 0)
{
x += secs.ToString();
}
return x;
}
}
}
I'm not sure if this causes your problem, but you should use int instead of double, as the TimeSpan members are int anyway. Comparing double to an exact number can cause problems
int hours = ts_timeElapsed.Hours;
int mins = ts_timeElapsed.Minutes;
int secs = ts_timeElapsed.Seconds;

Categories

Resources