C#里有没有类似于C++ 的 setTime 一样的函数

来源:百度知道 编辑:UC知道 时间:2024/06/09 20:30:36
我想实现在网页上的一个时钟, 用一个像setTime一样的函数,每一秒获取一下当前时间,然后赋值给页面上的Label。 这样就成了一个时钟了。
可是不知道C#有没有 这样的方法。

C# 有的呀...

Timer 就是

例子:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public DateTime dt = new DateTime();
public Label hLabel = new Label();
public Label mLabel = new Label();
public Label sLabel = new Label();
public Form1()
{
InitializeComponent();
Timer timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
}

void timer_Tick(object sender, EventArgs e)
{
hLabel.Text = DateTime.Now.Hour;
mLabel.Text = DateTime.Now.Minute;
sLabel.Text = DateTime.Now.Second;
}
}
}

可以做到 不过不建议这么用,这样服务器的负担会很重。 建议你在页面打开的时候把服务器当前的时间赋值给控件, 然后在客户端用JS 获取这个时间,再每一秒把这个时间加1. 具体代码你搜一下,很多的。

网页WEB控件中没有这个东西,不过AJAX中有TIMER控件你可