Convert minutes to hours, minutes and seconds [closed]

穿精又带淫゛_ 提交于 2019-12-29 08:41:51

问题


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.


回答1:


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

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



回答2:


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.




回答3:


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

    }
}


来源:https://stackoverflow.com/questions/11459879/convert-minutes-to-hours-minutes-and-seconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!