C# 将分钟转换为小时、分钟和秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11459879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert minutes to hours, minutes and seconds
提问by alexy12
Im my interface I'm letting the user input X amount of minutes that they can pause an action for.
我是我的界面,我让用户输入他们可以暂停操作的 X 分钟数。
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.
我需要它来更新倒计时标签以向用户显示剩余时间。
回答by Dimitri
First create TimeSpan and then format it to whatever format you want:
首先创建 TimeSpan,然后将其格式化为您想要的任何格式:
TimeSpan span = TimeSpan.FromMinutes(minutes);
string label = span.ToString(@"hh\:mm\:ss");
回答by Dimitri
Create a new TimeSpan:
创建一个新的TimeSpan:
var pauseDuration = TimeSpan.FromMinutes(minutes);
You now have the convenient properties Hours, Minutes, and Seconds. I should think that they are self-explanatory.
您现在有方便的特性Hours,Minutes和Seconds。我应该认为它们是不言自明的。
回答by Mark Hall
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.
这应该给你一个开始的地方。定时器设置为 1000 毫秒。它使用与其他答案相同的想法,但更加充实。
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();
}
}
}
}

