2012-07-12 191 views
-2

即時消息我的界面我讓用戶輸入X分鐘數,他們可以暫停動作。將分鐘轉換爲小時,分鐘和秒

如何將其轉換爲小時,分鐘和秒?

我需要它來更新倒計時標籤以向用戶顯示剩下的時間。

+8

[你有什麼試過](http://mattgemmell.com/2008/12/08/what-have-you-tried/)? – 2012-07-12 20:15:40

+0

我只能將其轉換爲一種格式,但我需要計算小時,分鐘和秒 – alexy12 2012-07-12 20:16:14

+0

用戶條目的格式是什麼? – 2012-07-12 20:17:06

回答

37

首先創建時間跨度,然後將其格式化爲任何你想要的格式:

TimeSpan span = TimeSpan.FromMinutes(minutes); 
string label = span.ToString(@"hh\:mm\:ss"); 
9

創建一個新的TimeSpan

var pauseDuration = TimeSpan.FromMinutes(minutes); 

您現在有方便的特性HoursMinutesSeconds。我應該認爲它們是不言自明的。

1

這是應該給你啓動的地方。定時器設置爲1000ms。它使用與其他答案相同的想法,但充實了更多。

public partial class Form1 : Form 
{ 
    TimeSpan duration; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     duration = duration.Subtract(TimeSpan.FromSeconds(1)); //Subtract a second and reassign 
     if (duration.Seconds < 0) 
     { 
      timer1.Stop(); 
      return; 
     } 

     lblHours.Text = duration.Hours.ToString(); 
     lblMinutes.Text = duration.Minutes.ToString(); 
     lblSeconds.Text = duration.Seconds.ToString(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     if(!(string.IsNullOrEmpty(textBox1.Text))) 
     { 
      int minutes; 
      bool result = int.TryParse(textBox1.Text, out minutes); 
      if (result) 
      { 
       duration = TimeSpan.FromMinutes(minutes); 
       timer1.Start(); 
      } 
     } 

    } 
} 
相關問題