时间跨度转换 [英] TimeSpan Conversion

查看:134
本文介绍了时间跨度转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将分钟转换为秒,此刻我有一个问题,因为在分钟文本框中,当我键入1.50时,结果是90秒,这是错误的,因为1.30 = 90秒

I want to convert minutes to seconds and at the moment I have a problem because in the minute textbox when I type 1.50 the outcome is 90 seconds which is wrong because 1.30 = 90 seconds

    private void MtoCbutton_Click(object sender, EventArgs e)
    {
        if (minTosecTextBox.Text != "Minutes")
        {
            minutes = Convert.ToDouble(minTosecTextBox.Text);
            TimeSpan span = TimeSpan.FromMinutes(minutes);
            resultSectextBoxtextBox.Text = span.TotalSeconds.ToString();
        }

        else
        {

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

推荐答案

要将秒转换为分钟,您只需要除以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.

这篇关于时间跨度转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆