2012-07-12 186 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(); 
      } 
     } 

    } 
}