一、效果
二、实现代码
DateTime dtNow, dtSet;//定义两个DateTime类型的变量,分别用来记录当前时间和设置的到期时间
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 1000;//设置timer1计时器的执行时间间隔
timer1.Enabled = true;//启动timer1计时器
numericUpDown1.Value = DateTime.Now.Hour;//显示当前时
numericUpDown2.Value = DateTime.Now.Minute;//显示当前分
numericUpDown3.Value = DateTime.Now.Second;//显示当前秒
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "设置")//判断按钮的文本是否为设置
{
button1.Text = "停止";//设置按钮的文本为停止
timer2.Start();//启动timer2计时器
}
else if (button1.Text == "停止")//判断按钮的文本是否为停止
{
button1.Text = "设置";//设置按钮的文本为设置
timer2.Stop();//停止timer2计时器
label3.Text = "倒计时已取消";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
label7.Text = DateTime.Now.ToLongTimeString();//显示系统时间
dtNow = Convert.ToDateTime(label7.Text);//记录系统时间
}
private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void timer2_Tick(object sender, EventArgs e)
{
//记录设置的到期时间
dtSet = Convert.ToDateTime(numericUpDown1.Value + ":" + numericUpDown2.Value + ":" + numericUpDown3.Value);
//计算倒计时
long countdown = DateAndTime.DateDiff(DateInterval.Second, dtNow, dtSet, FirstDayOfWeek.Monday, FirstWeekOfYear.FirstFourDays);
if (countdown > 0)//判断倒计时时间是否大于0
label3.Text = "倒计时已设置,剩余" + countdown + "秒";//显示倒计时
else
label3.Text = "倒计时已到";
}