利用timer实现倒计时
private int GetDay(int year, int month)
{
int result = 31; // 默认月份对应的天数为31天
switch (month)
{
case 4:
case 6:
case 9:
case 11:
result = 30; // 4月、6月、9月、11月只有30天
break;
case 2:
if ((year % 100 != 0) && (year % 4 == 0) || (year % 400 == 0))
{
result = 29; // 如果是闰年,则2月有29天
}
else
{
result = 28; // 否则2月有28天
}
break;
}
return result; // 返回该月份的天数
}
private void GetControls1(Control fatherControl)
{
Control.ControlCollection sonControls = fatherControl.Controls; // 获取父控件的子控件集合
// 遍历所有控件
foreach (Control control in sonControls)
{
if (control is Button)
{
Button t = (Button)control;
t.Enabled = false; // 将按钮控件的Enabled属性设为false,禁用按钮
}
if (control.Controls != null)
{
GetControls1(control); // 递归调用,处理子控件的子控件
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
DateTime observeTime = DateTime.Parse("2024-04-20 18:10:30"); // 设定倒计时的目标时间
DateTime now = DateTime.Now; // 获取当前时间
TimeSpan ts = observeTime.Subtract(now); // 计算目标时间与当前时间的时间差
StringBuilder result = new StringBuilder(); // 用于存放时间差结果的字符串
int year = observeTime.Year - now.Year; // 计算年份差
int month = observeTime.Month - now.Month; // 计算月份差
int day = observeTime.Day - now.Day; // 计算天数差
int hmh = (observeTime.Hour - now.Hour) * 3600 + (observeTime.Minute - now.Minute) * 60 + (observeTime.Second - now.Second); // 计算时分秒差的总秒数
// 如果目标时间的时分秒比当前时间晚
if (hmh <= 0)
{
day--; // 天数减一
// 若天数小于等于0,且月份大于0,或者天数小于等于0,年份大于0,则向月份借一天
if ((day <= 0 && month > 0) || (day <= 0 && year > 0))
{
// 如果天数小于等于0,向月份借一天,并更新月份和年份
day = GetDay(now.Year, now.Month) - now.Day + observeTime.Day;
month--;
if (month < 0 && year > 0)
{
// 如果月份小于0,向年份借一,并将月份转为正数
month += 12;
year--;
}
}
}
// 如果天数小于0,且月份大于0,或者天数小于0,年份大于0,则向月份借一天
if ((day < 0 && month > 0) || (day < 0 && year > 0))
{
// 如果天数小于0,向月份借一天,并更新月份和年份
day = GetDay(now.Year, now.Month) - now.Day + observeTime.Day;
month--;
if (month < 0 && year > 0)
{
// 如果月份小于0,向年份借一,并将月份转为正数
month += 12;
year--;
}
}
// 如果月份小于0,向年份借一,并将月份转为正数
if (month < 0 && year > 0)
{
month += 12;
year--;
}
// 如果年份小于0,或者年份等于0且月份小于0,或者年份等于0、月份等于0且天数小于0,说明已超过目标日期
if (year < 0 || (year == 0 && month < 0) || (year == 0 && month == 0 && day < 0))
{
GetControls1(this); // 禁用所有按钮控件
return;
}
// 拼接时间差的结果
if (year > 0)
{
result.Append(year + "年");
}
if (month > 0)
{
result.Append(month + "月");
}
if (day > 0)
{
result.Append(day + "天");
}
if (ts.Hours > 0)
{
result.Append(ts.Hours + "时");
}
if (ts.Minutes > 0)
{
result.Append(ts.Minutes + "分");
}
if (ts.Seconds > 0)
{
result.Append(ts.Seconds + "秒");
}
if (result.Length == 0)
{
result.Append("已超过日期"); // 若时间差为0,则说明已超过目标日期
}
// label2.Text = "软件使用有效期:" + result.ToString(); // 将时间差结果显示在界面上
}
文章详细描述了如何使用C#中的Timer控件实现一个倒计时功能,同时处理日期跨越的情况,如闰年和目标日期之前的调整。作者还展示了如何禁用特定的按钮以及更新界面显示时间差。
6341

被折叠的 条评论
为什么被折叠?



