帮助倒计时应用程序。 [英] Help with a countdown app.
问题描述
我正在尝试做两件事:
在圣诞节那天,每当导航到页面时都会调用一个方法。
On Christmas day, invoke a method whenever the page is navigated to.
圣诞节过后,将christmasDay DateTime设置为+1年(因此倒计时"重置")。
After Christmas day, set the christmasDay DateTime to +1 year (so the countdown "resets").
这是我的代码:
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);
}
当我将日期设置为TODAY时,"itsChristmas()"方法有效...但我实际上并不希望在倒计时的每个刻度上调用它。我尝试将它放在页面的构造函数中,但这不起作用。有什么想法吗?
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. :(
推荐答案
你'如果你已经调用了今年的圣诞节功能,那么很可能必须在隔离存储器中存储一个标志。我将保存最后一次将圣诞节功能称为日期时间。
You'll most likely have to store a flag in isolated storage to set if you've already called the Christmas function for this year. I'd save the last time the Christmas function was called as a DateTime.
这可能有用。 :
This may work. :
// I'll use Dec 25 for my Christmas countdown...
DateTime nextChristmas = new DateTime(DateTime.Year(), 12, 25);
if(DateTime.Now.Date == nextChristmas.Date && ReadIsolatedStorageDate() != DateTime.Now.Date)
{
SaveIsolatedStorageDate(DateTime.Now.Date);
itsChristmas();
}
else if(DateTime.Now.Date == nextChristmas.Date)
nextChristmas = new DateTime(DateTime.Now.Year+1, 12, 25);
// this contains the time remaining until this Christmas, or next Christmas, depending.
TimeSpan countdown = nextChristmas - DateTime.Now;
ReadIsol atedStorageDate和SaveIsolatedStorageDate函数留给您自己的练习,但只保存或加载传递的日期和时间。
The ReadIsolatedStorageDate and SaveIsolatedStorageDate functions are left for your own exercise, but just save or load the dates and times passed.
ie:
DateTime ReadIsolatedStorageDate();
{
}
和
void SaveIsolatedStorageDate(DateTime date)
{
}
这篇关于帮助倒计时应用程序。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!