Convert minutes to hours, minutes and seconds [clo

2019-01-28 23:50发布

Im my interface I'm letting the user input X amount of minutes that they can pause an action for.

How can i convert that into hours, minutes and seconds?

I need it to update the countdown labels to show the user the time left.

标签: c# timer
3条回答
冷血范
2楼-- · 2019-01-29 00:25

First create TimeSpan and then format it to whatever format you want:

TimeSpan span = TimeSpan.FromMinutes(minutes);
string label = span.ToString(@"hh\:mm\:ss");
查看更多
等我变得足够好
3楼-- · 2019-01-29 00:39

This is something that should give you someplace to start. The Timer is set for 1000ms. It is using the same ideas as the other answers but fleshed out a bit more.

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();
            }
        }

    }
}
查看更多
唯我独甜
4楼-- · 2019-01-29 00:48

Create a new TimeSpan:

var pauseDuration = TimeSpan.FromMinutes(minutes);

You now have the convenient properties Hours, Minutes, and Seconds. I should think that they are self-explanatory.

查看更多
登录 后发表回答