[英]How to display updated time as system time on a label using c#?
我想使用C#在標簽上顯示當前時間,但是時間會隨着系統時間的變化而不斷變化。 我怎樣才能做到這一點?
將一個新的Timer控件添加到窗體中,稱為Timer1,將時間間隔設置為1000(ms),然后雙擊Timer控件以編輯Timer1_Tick的代碼並添加以下代碼:
this.label1.Text = DateTime.Now.ToString();
添加一個設置為每秒觸發一次(1000毫秒)的Timer
控件。 在該計時器的Tick
事件中 ,您可以使用當前時間更新標簽。
您可以使用類似DateTime.Now
方法獲取當前時間。
您可以添加一個計時器控件並將其指定為1000毫秒間隔
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt");
}
嘗試以下代碼:
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("hh:mm:ss");
}
您必須在代碼或屬性窗口中將計時器也設置為啟用。
在代碼中,請在表單加載部分中鍵入以下內容:
myTimer.Enabled = true;
myTimer.Interval = 1000;
之后,請確保您的計時器事件與此類似:
private void myTimer_Tick(object sender, EventArgs e)
{
timeLabel.Text = DateTime.Now.ToString("hh:mm:ss");
}
由於計時器間隔不正確,因此您的更新可能無法同步,並且會相對於實際秒數轉換發生偏移。 在某些情況下,您將滯后或落后於轉換,並錯過時間顯示中的更新
此方法可能會給您一些尊重,而不是在幾秒鍾的更改后以高頻率輪詢一次來觸發更新。
如果您喜歡調節器,則可以通過使用要顯示的時間戳的毫秒屬性來調整1000 ms計時器,從而將時間更新調整為在實際第二次轉換后100 ms安全地定位。
在計時器事件代碼中執行以下操作:
//Read time
DateTime time = DateTime.Now;
//Get current ms offset from prefered readout position
int diffms = time.Millisecond-100;
//Set a new timer interval with half the error applied
timer.Interval = 1000 - diffms/2;
//Update your time output here..
然后,下一個計時器間隔應在秒數轉換后100毫秒內觸發接近所選點。 當處於過渡狀態+ 100ms時,錯誤將切換+/-,以保持您的讀數位置及時。
private int hr, min, sec;
public Form2()
{
InitializeComponent();
hr = DateTime.UtcNow.Hour;
min = DateTime.UtcNow.Minute;
sec = DateTime.UtcNow.Second;
}
//Time_tick click
private void timer1_Tick(object sender, EventArgs e)
{
hr = DateTime.UtcNow.Hour;
hr = hr + 5;
min = DateTime.UtcNow.Minute;
sec = DateTime.UtcNow.Second;
if (hr > 12)
hr -= 12;
if (sec % 2 == 0)
{
label1.Text = +hr + ":" + min + ":" + sec;
}
else
{
label1.Text = hr + ":" + min + ":" + sec;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.