且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

时间跨度转换

更新时间:2023-02-26 16:20:35

要将秒转换为分钟,您只需要除以60.0(您需要使用小数,否则它将被视为整数).如果将其视为整数,并且您经过30秒,则30/60将等于0.

To convert from seconds to minutes you simply need to divide by 60.0 (you need the decimal or it will be treated like an integer). If treated like an integer and you pass 30 seconds, 30/60 will equal 0.

也可以使用double.TryParse方法.现在,如果有人输入1.50xx,您的应用程序将崩溃.使用double.TryParse方法或使用try catch机制或仅允许数字输入.

Also use double.TryParse method. Right now if someone enters 1.50xx, your application will crash. Either use double.TryParse method or use a try catch mechanism or only allow numeric entry.

编辑

这将完成您想要的.我添加了一个标签来显示输出,但是您可以将其删除.

This will accomplish what you want. I added a label to show the output but you can remove it.

double enteredNumber;
if (double.TryParse(minTosecTextBox.Text, out enteredNumber))
{
    // This line will get everything but the decimal so if entered 1.45, it will get 1
    double minutes = Math.Floor(enteredNumber);

    // This line will get the seconds portion from the entered number.
    // If the number is 1.45, it will get .45 then multiply it by 100 to get 45 secs
    var seconds = 100 * (enteredNumber - Math.Floor(enteredNumber));

    // now we multiply minutes by 60 and add the seconds
    var secondsTotal = (minutes * 60 + seconds);

    this.labelSeconds.Text = secondsTotal.ToString();
}

else
{

    MessageBox.Show("Please enter Minutes");
}

编辑2

需要进一步澄清

您没有将分钟转换为秒,因为如果您当时为1.5(1分半)则等于90秒.这是合乎逻辑的,也是显而易见的.您只将小数点前的部分视为分钟,而将小数点后的部分视为秒(1.30 = 1分钟和30秒= 90秒). 因此,我们只需要将小数点前的部分转换为秒,然后将小数点后的部分添加到其中.

You are not converting minutes to seconds since if you were then 1.5 (1 minute and a half) would equal 90 seconds. This is logical and obvious. You are treating only the part before the decimal as minutes and the part after the decimal is to be treated as seconds (1.30 = 1 minute and 30 seconds = 90 seconds). Therefore we only need to convert the part before the decimal to seconds and add to it the part after the decimal.